import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import {
  Component,
  OnInit,
  ViewChild,
  ViewContainerRef,
  ComponentFactoryResolver,
  ComponentRef,
  ComponentFactory,
  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 { ContactsPage } from './messages/contacts/contacts.page';
import { MessagesPage } from './messages/messages.page';
import { NewGroupPage } from './new-group/new-group.page';
import { Storage } from '@ionic/storage';
import { AlertService } from 'src/app/services/alert.service';
import { EditGroupPage } from 'src/app/shared/chat/edit-group/edit-group.page';
import * as Rx from "rxjs/Rx";
import { Message } from 'src/app/models/message.model';
import { Observable, Subject } from "rxjs/Rx";
import { NavigationStart, NavigationEnd, Router } from '@angular/router';
import { EventPerson } from 'src/app/models/eventperson.model';
import { removeDuplicate } from 'src/plugin/removeDuplicate.js'
import { environment } from 'src/environments/environment';
import { NotificationsService } from 'src/app/services/notifications.service';

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

  showLoader: boolean;

  headers: HttpHeaders;
  options:any;
  X_User_Id:any;
  X_Auth_Token:any;

  loggedUser: any;
  /* Set segment variable */
  segment:string;
  allGroups: any[];
  privateGroups: any[];
  publicGroups: any[];
  userConnectedList: any[];
  userRooms: any[];
  userChannels: any[];
  userDirectMessages: any[];
  result:any;
  dmUsers:any[] = [];
  idSelected: string;

  desktopComponent: any = {
    showMessages: false,
    showGroupMessages: false,
  }

  @ViewChild('messagecontainer', { read: ViewContainerRef }) entry: ViewContainerRef;
  //@ViewChild('groupMessages') child:GroupMessagesPage;
  componentRef: any;

  roomId:any;
  groupRoomId:any;
  showEmptyComponent=true;
  showMessages=false;
  showContacts=false;
  showNewGroup=false;
  showEditGroup=false;
  showGroupMessages=false;
  showGroupContacts=false;
  showNewEvent=false;
  showAttendees=false;
  emptyTextDescription = 'Sem conversa selecionada';

  @Output() getRoomInfo;


  /*

  Websockets variables

  */

  subject: any;
  public messages: Subject<any>;

  message = {
    "msg": "connect",
    "version": "1",
    "support": ["1"]
  };


  /*  Fim websockets variables*/
  loggedUserChat:any;
  hideRefreshBtn = true;

  taskParticipants: any = [];
  taskParticipantsCc: any = [];
  adding: "intervenient" | "CC" = "intervenient";
  profile:'mdgpr' | 'pr';
  eventSelectedDate: Date = new Date();
  contacts:  EventPerson[];
  showEventEditOrOpen:  "edit" | "add" | "" | "eventoToApprove" = ""

  constructor(
    private http:HttpClient,
    private chatService: ChatService,
    private modalController: ModalController,
    private authService: AuthService,
    private storage:Storage,
    private resolver: ComponentFactoryResolver,
    private route: Router,
    ){
      this.loggedUserChat = authService.ValidatedUserChat['data'];
      this.headers = new HttpHeaders();

    }

  ngOnInit() {
    console.log(this.loggedUserChat);

    this.segment = "Contactos";

    this.authService.userData$.subscribe((res:any)=>{
      this.loggedUser=res;
      console.log(this.loggedUser);
      this.load();
    });

  /* websocket functions */
  //this.sendMsg();

  /* Fim websocket functions */
  this.hideRefreshButton();
  this.getChatMembers();

  //Teste
  let t = this.showDateDuration(new Date());
  console.log(t);

  this.setStatus('away');
}

ngOnDestroy(){
  this.setStatus('offline');
  console.log('On Destroy')
}

setStatus(status:string){
  let body = {
    message: '',
    status: status,
  }
  this.chatService.setUserStatus(body).subscribe(res => {
    console.log(res);
  })
}

hideRefreshButton(){
  window.onresize = (event) => {
    if( window.innerWidth < 701) {
      this.idSelected = '';
      this.hideRefreshBtn = false;
    }
    else{
      this.hideRefreshBtn = true;
      if(this.idSelected == ''){
        this.showEmptyComponent=true;
      }
    }
  }
  if(window.innerWidth < 701){
    this.idSelected = '';
    this.hideRefreshBtn = false;
  }
}


/* loadMessage(){
  this.chatService.messages.subscribe(msg => {
    console.log("Response from websocket: " + msg);
  });
} */
/* sendMsg() {
  console.log("new message from client to websocket: ", this.message);
  this.chatService.messages.next(this.message);
  this.message.msg = "";
} */


  /* Fim websockets functions */

  closeAllDesktopComponents() {
    this.showMessages=false;
    this.showContacts=false;
    this.showNewGroup=false;
    this.showEditGroup=false;
    this.showGroupMessages=false;
    this.showEmptyComponent=false;
    this.showGroupContacts=false;
    this.showNewEvent=false;
    this.showAttendees=false;
    console.log('All components closed!');
  }

  showEmptyContainer(){
    this.idSelected = '';
    this.showEmptyComponent=true;
  }
  openGroupContactsPage(data){
    this.idSelected = '';
    this.groupRoomId = data;
    this.closeAllDesktopComponents();
    if(window.innerWidth < 801){

    }
    else{
      this.showGroupContacts = true;
    }
  }
  openMessagesPage(rid) {
    if( window.innerWidth < 701){
      this.openMessagesModal(rid);
      //this.router.navigate(['/home/chat/messages',rid,]);
    }
    else{
      this.idSelected = rid;
      this.closeAllDesktopComponents();
      this.showEmptyComponent = false;
      this.roomId = rid;
      this.showMessages=true;
    }
  }
  openContactsPage() {
    console.log('OK');
    this.idSelected = '';
    this.closeAllDesktopComponents();

    if( window.innerWidth < 701){
      this.selectContact();
    }
    else{
      console.log('here');
      this.showContacts=true;
    }
  }
  openNewGroupPage() {
    this.idSelected = '';
    if( window.innerWidth < 801){
      this.newGroup();
    }
    else{
      this.closeAllDesktopComponents();
      this.showNewGroup=true;
    }
  }

  openEditGroupPage(rid) {
    if( window.innerWidth < 801){
      this.editGroup(rid);
    }
    else{
      this.closeAllDesktopComponents();
      this.showEditGroup=true;
    }
  }

  openGroupMessagesPage(rid) {
    console.log(rid);

    if( window.innerWidth < 701){
      this.openGroupMessagesModal(rid);
    }
    else{
      this.idSelected = rid;
      this.closeAllDesktopComponents();
      this.showEmptyComponent = false;
      this.roomId = rid;
      console.log(this.roomId);
      this.showGroupMessages=true;
    }
  }

  openNewEventPage(data:any){
    this.taskParticipants = data.members.map((val) =>{
      return {
        Name: val.name,
        EmailAddress: val.username+"@"+environment.domain,
        IsRequired: "true",
      }
    });
    this.closeAllDesktopComponents();
    if(window.innerWidth < 701){
      console.log('Mobile');
    }
    else{
      this.showNewEvent=true;
    }
  }

  async openAttendeesComponent(data) {
    this.adding = data.type
    this.closeAllDesktopComponents();
    this.showAttendees = true;
  }

  async clearContact() {
    this.contacts = [];
  }

  async setContact(data:EventPerson[]) {
    this.contacts = data;
  }

  async setIntervenient(data) {
    this.taskParticipants = removeDuplicate(data)

  }

  async setIntervenientCC(data) {
    this.taskParticipantsCc = removeDuplicate(data)
  }

  async closeAttendeesComponent() {
    this.closeAllDesktopComponents();
      this.showNewEvent = true;
  }

  async closeNewEventComponent() {
    this.closeAllDesktopComponents();
    this.showEmptyComponent = true;
    this.idSelected = "";
  }

  onSegmentChange(){
    this.load();
  }

  doRefresh(event){
    setTimeout(() => {
      this.load();
      event.target.complete();
    }, 1000);
  }

  refreshing(){
    this.load();
  }

  load(){
    switch (this.segment)
    {
      case "Contactos":
        this.getDirectMessages();
        break;

      case "Grupos":
        this.getGroups();
        break;
    }
  }
  customRoom(){
    let params = new HttpParams();
    params = params.set("types", "c");
    this.chatService.customsRooms(params).subscribe(res=>{
      console.log(res);
    });
  }

  async getDirectMessages(){

    this.chatService.getAllDirectMessages().subscribe(async (res:any)=>{

      if(res.ims != 200){
        console.log(res.ims);
        this.userDirectMessages = res.ims.sort((a,b)=>{
          var dateA = new Date(a._updatedAt).getTime();
          var dateB = new Date(b._updatedAt).getTime();
          return dateB - dateA;
        });
        console.log(this.userDirectMessages);

        if(this.route.url != "/home/chat"){
          console.log("Timer message stop")
        }
        else {
          //Check if modal is opened
          if(this.segment == "Contactos" && this.showMessages != true){
            await new Promise(resolve => setTimeout(resolve, 5000));
            await this.getDirectMessages();
            console.log('Timer contactos list running')
          }
        }
      }
      else{
        await this.getDirectMessages();
      }
    });
  }

  showDateDuration(start:any){
    let end;
    end = new Date();
    start = new Date(start);
    let customizedDate;

    const totalSeconds     = Math.floor((end - (start))/1000);;
    const totalMinutes     = Math.floor(totalSeconds/60);
    const totalHours       = Math.floor(totalMinutes/60);
    const totalDays        = Math.floor(totalHours/24);

    const hours   = totalHours - ( totalDays * 24 );
    const minutes = totalMinutes - ( totalDays * 24 * 60 ) - ( hours * 60 );
    const seconds = totalSeconds - ( totalDays * 24 * 60 * 60 ) - ( hours * 60 * 60 ) - ( minutes * 60 );

    if(totalDays == 0){
      if(start.getDate() == new Date().getDate()){
        let time = start.getHours() + ":" + this.addZero(start.getUTCMinutes());
        return time;
      }
      else{
        return 'Ontem';
      }
    }
    else{
      let date = start.getDate() + "/" + (start.getMonth()+1) + "/" + start.getFullYear();
      return date;
    }
  }

  addZero(i) {
    if (i < 10) {
      i = "0" + i;
    }
    return i;
  }

  async getChatMembers(){
    //return await this.chatService.getMembers(roomId).toPromise();
    this.chatService.getAllUsers().subscribe(res=> {
      console.log(res);

      this.dmUsers = res['users'].filter(data => data.username != this.loggedUserChat.me.username);
      console.log(this.dmUsers);
    });
  }

  async getGroups(){
    this.result = this.chatService.getAllPrivateGroups().subscribe(async (res:any)=>{

    if(res.groups != 200){

      this.privateGroups = res.groups;
      /* this.result = this.chatService.getAllUserChannels().subscribe((res:any)=>{
        this.publicGroups = res.channels; */
        //let all = this.privateGroups.concat(this.publicGroups);
        this.allGroups = this.privateGroups.sort((a,b)=>{
          var dateA = new Date(a._updatedAt).getTime();
          var dateB = new Date(b._updatedAt).getTime();
          return dateB - dateA;
        });
        console.log(this.allGroups);
      /* }); */
      if(this.route.url != "/home/chat"){
        console.log("Timer message stop")
      }
      else {
        //Check if modal is opened
        if(this.segment == "Grupos" && this.showGroupMessages != true){
          await new Promise(resolve => setTimeout(resolve, 5000));
          await this.getGroups();
          console.log('Timer groups list running')
        }
      }

    }
    else{
      await this.getGroups();
    }

    });
  }

  async selectContact(){
    const modal = await this.modalController.create({
      component: ContactsPage,
      cssClass: 'modal modal-desktop',
    });
    await modal.present();
    modal.onDidDismiss();
  }

  async newGroup(){
    const modal = await this.modalController.create({
      component: NewGroupPage,
      cssClass: 'modal modal-desktop',
    });
    await modal.present();
    modal.onDidDismiss();
  }

  async editGroup(roomId){
    const modal = await this.modalController.create({
      component: EditGroupPage,
      cssClass: 'modal modal-desktop',
      componentProps: {
        roomId: roomId,
      },
    });
    await modal.present();
    modal.onDidDismiss().then((res)=>{
      console.log(res.data);
      this.modalController.dismiss(res.data);
    });
  }

  async openMessagesModal(roomId:any){
    this.closeAllDesktopComponents();

    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 openGroupMessagesModal(roomId:any){

    console.log(roomId);

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

}
