import {Component, inject, OnInit} from '@angular/core'
import {Observable, of} from 'rxjs'
import {IProfile} from '../../models/IProfile'
import {DatabaseService} from '../services/database.service'
import {Router} from '@angular/router'

@Component({
  selector: 'app-new-channel',
  templateUrl: './new-channel.page.html',
  styleUrls: ['./new-channel.page.scss'],
})
export class NewChannelPage implements OnInit {

  #dbService = inject(DatabaseService)
  #router = inject(Router)

  newChannelName = ''
  isPublic = true
  users: Promise<IProfile[]> = this.#dbService.retrieveMatchingUsers('')
  addedUsers = new Set<string>()
  userName = ''

  constructor() { }

  ngOnInit() {
  }

  async createChannel(): Promise<void> {
    await this.#dbService.createChannel(this.newChannelName, this.isPublic, Array.from(this.addedUsers))
    await this.#router.navigate(['channel', this.newChannelName])
  }

  async retrieveUsers(): Promise<void> {
    this.users = this.#dbService.retrieveMatchingUsers(this.userName)
  }

  toggleUser(id: string) {
    if (this.addedUsers.has(id)) {
      this.addedUsers.delete(id)
    } else {
      this.addedUsers.add(id)
    }
  }

  ionViewWillEnter() {
    console.log('Entered new channel page, resetting view.')
    this.newChannelName = ''
    this.isPublic = true
    this.users = new Promise((r) => r([]))
    this.addedUsers = new Set<string>
    this.userName = ''
  }
}
