import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { AuthService } from 'src/app/services/auth.service';
import { ChatService } from 'src/app/services/chat.service';
import { GroupMessagesPage } from '../../group-messages/group-messages.page';
import { MessagesPage } from '../messages.page';
import { ThemeService } from 'src/app/services/theme.service'

@Component({
  selector: 'app-contacts',
  templateUrl: './contacts.page.html',
  styleUrls: ['./contacts.page.scss'],
})
export class ContactsPage implements OnInit {
  showLoader: boolean;
  loggedUser: any;
  users = [];

  headers: HttpHeaders;
  options:any;
  contacts:any;
  textSearch:string;
  room:any;
  dm:any;

  @Output() openMessage:EventEmitter<any> = new EventEmitter<any>();

  constructor(
    private modalController: ModalController,
    private http: HttpClient,
    private chatService: ChatService,
    private authService: AuthService,
    public ThemeService: ThemeService
  )
  {
    this.loggedUser = authService.ValidatedUserChat['data'];
    this.textSearch="";
    this.dm=null;
    this.room=null;
  }

  ngOnInit() {
    this.loadUsers();
  }

  onChange(event){
    this.textSearch = event.detail.value;
  }

  openMessagesPage(username:string){
    if( window.innerWidth < 701){
      this.createRoom(username);
    }
    else{
      let body = {
        username: username,
      }
      this.chatService.createRoom(body).subscribe(res => {
        console.log(res);
        this.room = res['room'];
        this.openMessage.emit(this.room._id);
      });
    }
  }

  loadUsers(){
    this.options = {
      headers: this.headers,
    };
    this.chatService.getAllUsers().subscribe((res:any)=>{
      console.log(res.users);
      //this.contacts = res.users.filter(data => data.username != this.loggedUser.me.username);
      this.contacts = res.users.filter(data => data.username != this.loggedUser.me.username);
      this.users = this.contacts.sort((a,b) => {
        if(a.name < b.name){
          return -1;
        }
        if(a.name > b.name){
          return 1;
        }
        return 0;
      });
      this.showLoader = false;
    });
  }

  separateLetter(record, recordIndex, records){
    if(recordIndex == 0){
      return record.name[0];
    }

    let first_prev = records[recordIndex - 1].name[0];
    let first_current = record.name[0];

    if(first_prev != first_current){
      return first_current;
    }
    return null;
  }

  doRefresh(event){
  }

  close(){
    this.modalController.dismiss();
  }

  clicked(){
    console.log('clicked');
  }

  createRoom(username:string){
    let body = {
      username: username,
    }
    this.chatService.createRoom(body).subscribe(res => {
      console.log(res);
      this.room = res['room'];
      this.openMessagesModal(this.room._id);
    });
  }

  async openMessagesModal(roomId: any) {

    console.log(roomId);

    const modal = await this.modalController.create({
      component: MessagesPage,
      cssClass: 'modal modal-desktop isMessagesChatOpened',
      componentProps: {
        roomId: roomId,
      },
    });
    await modal.present();
    modal.onDidDismiss();
  }

  async openMessages(username:string){
    /* this.close(); */

    let dm:any;
    //Create new room
     this.createRoom(username);
    //Get direct messages (dm)
    /* this.getDirectMessage(this.room._id); */
    console.log(this.dm);


    /* const modal = await this.modalController.create({
      component: MessagesPage,
      cssClass: 'group-messages',
      backdropDismiss: false,
      componentProps: {
        dm: dm,
      },
    });
    await modal.present();
    modal.onDidDismiss(); */
  }

}
