import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import {
  Component,
  OnInit,
  ViewChild,
  ViewContainerRef,
  ComponentFactoryResolver,
  ComponentRef,
  ComponentFactory,
  Output,
} from '@angular/core';
import { ModalController, Platform } 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 { 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';
import { TimeService } from 'src/app/services/functions/time.service';
import { ThemeService } from 'src/app/services/theme.service'
import { DataService } from 'src/app/services/data.service';
import { SqliteService } from 'src/app/services/sqlite.service';
import { StorageService } from 'src/app/services/storage.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;


  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,
    private timeService: TimeService,
    public ThemeService: ThemeService,
    private dataService: DataService,
    private router: Router,
    private sqlservice: SqliteService,
    private platform: Platform,
    private storageservice: StorageService

  ) {
    this.loggedUserChat = authService.ValidatedUserChat['data'];
    this.headers = new HttpHeaders();
    window.onresize = (event) => {
      if (window.innerWidth > 701) {
        this.modalController.dismiss();
      }
    };
    this.showLoader = true;
  }

  ngOnInit() {

    console.log(this.loggedUserChat);

    this.segment = "Contactos";

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

      this.getDirectMessagesDB();
    });

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

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

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

    this.setStatus('away');
    /* if(this.dataService.get("newGroup")){
      this.openNewGroupPage();
    } */

    this.router.events.forEach((event) => {
      if (event instanceof NavigationStart && event.url.startsWith('/home/chat')) {
        if (this.dataService.get("newGroup")) {
          this.openNewGroupPage();
        }
        else{
          this.closeAllDesktopComponents();
          this.showEmptyComponent = true;
        }
      }
      else{
        this.dataService.set("newGroup", false);
      }
    });
  }

  numSequence(n: number): Array<number> {
    return Array(n);
  }

  ngOnDestroy() {
    this.setStatus('offline');
    this.dataService.set("newGroup", false);
    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) {
    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.groupRoomId = data.roomId;
    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.showLoader = true;
        this.getDirectMessages();
        break;

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


  getDirectMessagesDB() {
    if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
      this.storageservice.get("rooms").then((rooms) =>{

        this.userDirectMessages = rooms.sort((a, b) => {
          var dateA = new Date(a._updatedAt).getTime();
          var dateB = new Date(b._updatedAt).getTime();
          return dateB - dateA;
        });
        console.log('DIRECTMESSAGE FROM DB', this.userDirectMessages);

        console.log('ROOMS FROM DB', rooms)
      })

      this.storageservice.get('chatusers').then((users) => {
        this.dmUsers = users.filter(data => data.username != this.loggedUserChat.me.username);
      })
    } else {
      this.sqlservice.getAllChatRoom().then((rooms: any) => {
        console.log('ROOMS FROM DB', rooms)
        let roomsArray = [];
        rooms.forEach(element => {
          let roomListDB = {
            _id: element.Id,
            uids: this.isJson(element.Uids),
            usernames: this.isJson(element.Usernames),
            lastMessage: this.isJson(element.LastMessage),
            _updatedAt: element.UpdatedAt
          }
          if(element.customFields == "undefined") {
            roomsArray.push(roomListDB)
          }
        });

        this.userDirectMessages = roomsArray.sort((a, b) => {
          var dateA = new Date(a._updatedAt).getTime();
          var dateB = new Date(b._updatedAt).getTime();
          return dateB - dateA;
        });
        console.log('DIRECTMESSAGE FROM DB', this.userDirectMessages);

        console.log('ROOMS FROM DB', rooms)
      })

      this.sqlservice.getAllChatUsers().then((userslist: any) => {
        console.log('USERS FOM DB 1', userslist)
        let chatusersArray = [];
        userslist.forEach(element => {
          console.log('USERS FOM DB 2', element)
          let userListDB = {
            _id: element.Id,
            name: element.Name,
            username: element.Username
          }

          chatusersArray.push(userListDB);
        });

        this.dmUsers = chatusersArray.filter(data => data.username != this.loggedUserChat.me.username);

      })
    }
  }

  transformDataRoomList(data) {
    if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
      let roomsArray = [];
      data.forEach(element => {
        let roomList = {
          _id: element._id,
          uids: element.uids,
          usernames: element.usernames,
          lastMessage: element.lastMessage,
          _updatedAt: element._updatedAt
        }

        console.log(' Web TRANSFORM ROOM LIST', roomList)
        roomsArray.push(roomList)
      });

      this.storageservice.store('rooms', roomsArray);

    } else {
      data.forEach(element => {
        let roomList = {
          id: element._id,
          uids: element.uids,
          usernames: element.usernames,
          lastMessage: element.lastMessage,
          updatedat: element._updatedAt
        }

        console.log('TRANSFORM ROOM LIST', roomList)
        this.sqlservice.addChatListRoom(roomList);
      });
    }
  }

  transformDataUserList(users) {
    if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
      let usersArray = [];
      users.forEach(element => {
        console.log('TRANSFORM USER CHAT 1', element)
        let chatusers = {
          _id: element._id,
          name: element.name,
          username: element.username
        }
        console.log('TRANSFORM USER CHAT 2', chatusers)
        usersArray.push(chatusers);
      });
      this.storageservice.store('chatusers',usersArray);
    } else {
      users.forEach(element => {
        console.log('TRANSFORM USER CHAT 1', element)
        let chatusers = {
          id: element._id,
          name: element.name,
          username: element.username
        }
        console.log('TRANSFORM USER CHAT 2', chatusers)
        this.sqlservice.addChatListUsers(chatusers);
      });
    }
  }

  async getDirectMessages(event?) {
    this.chatService.getAllDirectMessages().subscribe(async (res: any) => {
      this.showLoader = false;
      this.transformDataRoomList(res.ims)
      this.getDirectMessagesDB()
      console.log('Chat list', res);

      if (res != 200) {
        /* if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
          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(res.ims);

        //console.log(this.userDirectMessages);

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

  showDateDuration(start: any) {
    return this.timeService.showDateDuration(start);
  }

  countDownDate(date: any, roomId: string) {
    return this.timeService.countDownDate(date, roomId);
  }

  async getChatMembers() {
    //return await this.chatService.getMembers(roomId).toPromise();
    this.chatService.getAllUsers().subscribe(res => {
      console.log('chatusers', res);
      this.transformDataUserList(res['users'])

      if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
        this.dmUsers = res['users'].filter(data => data.username != this.loggedUserChat.me.username);
      console.log(this.dmUsers);
      }

    });
  }

  getGroupsDB() {
    if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
      this.storageservice.get("grouprooms").then((rooms) =>{


        this.allGroups = rooms.sort((a, b) => {
          var dateA = new Date(a._updatedAt).getTime();
          var dateB = new Date(b._updatedAt).getTime();
          return dateB - dateA;
        });

        console.log('GROUPS FROM DB',  this.allGroups)
      })

      this.storageservice.get('chatusers').then((users) => {
        this.dmUsers = users.filter(data => data.username != this.loggedUserChat.me.username);
      })
    } else {
      this.sqlservice.getAllChatRoom().then((rooms: any) => {

        let roomsArray = [];
        rooms.forEach(element => {
          let fddf = this.isJson(element.LastMessage);
          let roomListDB = {
            _id: element.Id,
            customFields: this.isJson(element.customFields),
            name: element.name,
            lastMessage: this.isJson(element.LastMessage),
            _updatedAt: element.UpdatedAt
          }
          if(element.customFields != "undefined") {
            roomsArray.push(roomListDB)
          }
        });

        this.allGroups = roomsArray.sort((a, b) => {
          var dateA = new Date(a._updatedAt).getTime();
          var dateB = new Date(b._updatedAt).getTime();
          return dateB - dateA;
        });
        console.log('Group FROM DB', this.allGroups);

      })

    /*   this.sqlservice.getAllChatUsers().then((userslist: any) => {
        console.log('USERS FOM DB 1', userslist)
        let chatusersArray = [];
        userslist.forEach(element => {
          console.log('USERS FOM DB 2', element)
          let userListDB = {
            _id: element.Id,
            name: element.Name,
            username: element.Username
          }

          chatusersArray.push(userListDB);
        });

        this.dmUsers = chatusersArray.filter(data => data.username != this.loggedUserChat.me.username);

      }) */
    }

  }

  transformGroups(data) {
    if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
      let groupsArray = [];
      data.forEach(element => {
        let roomList = {
          _id: element._id,
          uids: element.uids,
          usernames: element.usernames,
          name: element.name,
          customFields: element.customFields,
          lastMessage: element.lastMessage,
          _updatedAt: element._updatedAt
        }

        console.log(' Web TRANSFORM ROOM LIST', roomList)
        groupsArray.push(roomList)
      });

      this.storageservice.store('grouprooms', groupsArray);

    } else {
      data.forEach(element => {
        let roomList = {
          id: element._id,
          uids: element.uids,
          usernames: element.usernames,
          customFields: element.customFields,
          name: element.name,
          lastMessage: element.lastMessage,
          updatedat: element._updatedAt
        }

        console.log('TRANSFORM ROOM LIST', roomList)
        this.sqlservice.addChatListRoom(roomList);
      });
    }

  }

  async getGroups(event?) {
    this.result = this.chatService.getAllPrivateGroups().subscribe(async (res: any) => {
      //console.log(res);
       this.showLoader = false;
      if (res.groups != 200) {

        this.transformGroups(res.groups);
        this.getGroupsDB();

        /* this.privateGroups = res.groups;
        this.transformGroups(res.groups);
        this.getGroupsDB();

        this.privateGroups = res.groups;
        console.log('Chat list group' , res); */
        //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, 1000));
            await this.getGroups();
          }
        }
      }
      else {
        await this.getGroups();
      }
    });
  }

  isJson(str) {
    try {
      JSON.parse(str);
    } catch (e) {
      return str;
    }
    return JSON.parse(str);
  }

  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();
  }

  //   this.crop.crop('path/to/image.jpg', {quality: 75})
  //   .then(
  //     newImage => console.log('new image path is: ' + newImage),
  //     error => console.error('Error cropping image', error)
  //   );

}
