import { Component, OnChanges, OnInit, Input, SimpleChanges, Output, EventEmitter, ViewChild, ElementRef, AfterViewChecked, AfterViewInit, OnDestroy} from '@angular/core';
import { ActionSheetController, AnimationController, MenuController, ModalController, PopoverController } from '@ionic/angular';
import { AlertService } from 'src/app/services/alert.service';
import { AuthService } from 'src/app/services/auth.service';
import { ChatService } from 'src/app/services/chat.service';
import { ChatPopoverPage } from 'src/app/shared/popover/chat-popover/chat-popover.page';
import { ContactsPage } from '../new-group/contacts/contacts.page';
import { NewGroupPage } from '../new-group/new-group.page';
import { GroupContactsPage } from './group-contacts/group-contacts.page';
import { Router } from '@angular/router'
import { ChatOptionsPopoverPage } from '../../popover/chat-options-popover/chat-options-popover.page';
import { ChatOptionsFeaturesPage } from 'src/app/modals/chat-options-features/chat-options-features.page';

@Component({
  selector: 'app-group-messages',
  templateUrl: './group-messages.page.html',
  styleUrls: ['./group-messages.page.scss'],
})
export class GroupMessagesPage implements OnInit, OnChanges, AfterViewInit, OnDestroy {
  showLoader: boolean;
  isGroupCreated:boolean;
  loggedUser: any;
  message:any;
  leaveStatus:any;
  messages:any;


  room:any = new Array();
  roomName:any;
  members:any;

  loggedUserChat:any;
  scrollingOnce:boolean = true;
  private scrollChangeCallback: () => void;
  currentPosition: any;
  startPosition: number;

  @Input() roomId:string;
  @Output() closeAllDesktopComponents:EventEmitter<any> = new EventEmitter<any>();
  @Output() showEmptyContainer:EventEmitter<any> = new EventEmitter<any>();
  @Output() openGroupContacts:EventEmitter<any> = new EventEmitter<any>();
  @Output() openEditGroupPage:EventEmitter<any> = new EventEmitter<any>();
  @Output() openNewEventPage:EventEmitter<any> = new EventEmitter<any>();

  @ViewChild('scrollMe') private myScrollContainer: ElementRef;

  constructor(
    private menu: MenuController,
    private modalController: ModalController,
    private actionSheetController: ActionSheetController,
    public popoverController: PopoverController,
    private chatService: ChatService,
    private authService: AuthService,
    private animationController: AnimationController,
    private alertService: AlertService,
    private route: Router
  ) {
    this.loggedUserChat = authService.ValidatedUserChat['data'];
    this.isGroupCreated = true;
  }
  ngOnChanges(changes: SimpleChanges): void {
    //this.getRoomInfo();
    //this.scrollToBottom();
  }

  ngOnInit() {
    this.loggedUser=this.loggedUserChat;
    this.getRoomInfo();
    this.serverLongPull();
    console.log(this.roomId);
    this.setStatus('online');
  }

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

  scrollToBottom(): void {
    try {
      if(this.scrollingOnce){
        this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
      }
    } catch(err) { }
  }

  ngAfterViewInit() {
    this.scrollChangeCallback = () => this.onContentScrolled(event);
    window.addEventListener('scroll', this.scrollChangeCallback, true);
  }

   onContentScrolled(e) {
    this.startPosition = e.srcElement.scrollTop;
    let scroll = e.srcElement.scrollTop;
    if (scroll > this.currentPosition) {
      //this.showButton = false;
      //alert('BOTTOM');
    } else {
      //this.showButton = true;
      //alert('UP');
      this.scrollingOnce = false;
    }
    this.currentPosition = scroll;
  }

  ngOnDestroy() {
    this.setStatus('away');
    window.removeEventListener('scroll', this.scrollChangeCallback, true);
  }

  openGroupContactsPage(){
    this.openGroupContacts.emit(this.roomId);
  }

  openBookMeetingComponent(){
    let data = {
      roomId: this.roomId,
      members: this.members
    }
    this.openNewEventPage.emit(data);
  }

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

  doRefresh(ev:any){
    this.getRoomInfo();
    ev.target.complete();
  }

  get watch(){
    this.getRoomInfo();
    console.log('here watching');
    return this.roomId;
  }

  getRoomInfo(){
    this.showLoader = true;
    this.chatService.getRoomInfo(this.roomId).subscribe(room=>{
      this.room = room['room'];
      if(this.room.name){
        this.roomName = this.room.name.split('-').join(' ');
      }
      this.getGroupContacts(this.room);
      //this.loadGroupMessages(this.room);
      this.showLoader = false;
    });
  }

  getGroupContacts(room:any){
    this.showLoader = true;
    //If group is private call getGroupMembers
    if(room.t === 'p'){
      this.chatService.getGroupMembers(this.roomId).subscribe(res=>{
        console.log(res);
        this.members = res['members'];
        this.showLoader = false;
      });
    }
    //Otherwise call getChannelMembers for públic groups
    else{
      this.chatService.getChannelMembers(this.roomId).subscribe(res=>{
        console.log(res);
        this.members = res['members'];
        this.showLoader = false;
      });
    }
  }

  loadGroupMessages(roomId){
    //console.log('here'+room.t);

    this.showLoader = true;
    //If group is private call getGroupMembers
    /* if(room.t === 'p'){
      console.log('private'); */

      this.chatService.getPrivateGroupMessages(this.roomId).subscribe(res=>{
        console.log(res);
        let msgOnly = res['messages'].filter(data => data.t != 'au');
        this.messages = msgOnly.reverse();
        console.log(res);

        this.showLoader = false;
      });
  /*   } */
    //Otherwise call getChannelMembers for públic groups
    /* else{
      this.chatService.getPublicGroupMessages(this.roomId).subscribe(res=>{
        console.log(res);
        this.messages = res['messages'].reverse();
      });
    } */
  }

  sendMessage(){

    let body = {
      "message":
      {
        "rid": this.roomId, "msg": this.message
      }
    }

    this.chatService.sendMessage(body).subscribe(res=> {
     /*  this.loadGroupMessages(); */
     //this.getRoomInfo();
     this.scrollingOnce = true;
    });
    this.message = "";
  }
  async openGroupMessagesOptions() {

    const enterAnimation = (baseEl: any) => {
      const backdropAnimation = this.animationController.create()
        .addElement(baseEl.querySelector('ion-backdrop')!)
        .fromTo('opacity', '0.01', 'var(--backdrop-opacity)');

      const wrapperAnimation = this.animationController.create()
        .addElement(baseEl.querySelector('.modal-wrapper')!)
        .keyframes([
          { offset: 0, opacity: '1', right: '-100%' },
          { offset: 1, opacity: '1', right: '0px' }
        ]);

      return this.animationController.create()
        .addElement(baseEl)
        .easing('ease-out')
        .duration(500)
        .addAnimation([backdropAnimation, wrapperAnimation]);
    }

    const leaveAnimation = (baseEl: any) => {
      return enterAnimation(baseEl).direction('reverse');
    }


    /* const popover = await this.popoverController.create({
      component: MessagesOptionsPage,
      componentProps: {
        roomId: this.dm._id,
      },
      cssClass: 'messages-options',
      event: ev,
      translucent: true,
    });
    return await popover.present(); */

    const modal = await this.modalController.create({
      enterAnimation,
      leaveAnimation,
      component: ChatPopoverPage,
      cssClass: 'model profile-modal search-submodal',
      componentProps: {
        roomId: this.roomId,
      }
    });
    await modal.present();
    modal.onDidDismiss().then(res=>{
      console.log(res);
      if(res.data == 'leave'){
        this.leaveStatus = this.loggedUser.me.name + ' saiu do grupo';
      }
      else if(res.data == 'delete'){
        this.closeAllDesktopComponents.emit();
        this.showEmptyContainer.emit();
      }
      else if(res.data == 'cancel'){
        console.log('CANCEL');
      }
      else if(res.data == 'edit'){
        console.log(this.roomId);
        //this.closeAllDesktopComponents.emit();
        this.openEditGroupPage.emit(this.roomId);
      }
      else{
        this.roomName = res.data.name.split('-').join(' ');
        console.log(this.roomName);

        //this.getRoomInfo();
        this.loadGroupMessages(this.roomId);
        //this.modalController.dismiss();
      };

    });
  }

  openSendGroupMessageOptions(ev?: any){
    if(window.innerWidth <= 701){
      console.log('mobile');
      this.openChatOptions(ev);
    }
    else{
      console.log('desktop');
      this._openChatOptions();
    }
  }


  async openOptions(ev: any) {
    const popover = await this.popoverController.create({
      component: ChatPopoverPage,
      cssClass: 'chat-popover modal-desktop',
      event: ev,
      componentProps: {
        room: this.room,
      },
      translucent: true
    });
    await popover.present();
    popover.onDidDismiss().then(res=>{
      console.log(res);
      if(res.data){
        this.loadGroupMessages(this.roomId);
        //this.getRoomInfo();
        //this.modalController.dismiss();
      };

    });
  }
  async openChatOptions(ev: any) {
    const popover = await this.popoverController.create({
      component: ChatOptionsPopoverPage,
      cssClass: 'chat-options-popover',
      event: ev,
      componentProps: {
        room: this.room,
        members: this.members,
      },
      translucent: true
    });
    return await popover.present();
  }
  async addContacts(){
    console.log(this.members);

    const modal = await this.modalController.create({
      component: GroupContactsPage,
      componentProps: {
        isCreated: this.isGroupCreated,
        room: this.room,
        members: this.members,
        name: this.room.name,
      },
      cssClass: 'contacts',
      backdropDismiss: false
    });

    await modal.present();

    modal.onDidDismiss().then(()=>{
      //this.getRoomInfo();
      this.loadGroupMessages(this.roomId)
    });
  }

  /* async actionSheet() {
    const actionSheet = await this.actionSheetController.create({
      cssClass: 'my-custom-class',
      buttons: [{
        text: 'Sair do grupo',
        handler: () => {
          console.log('Delete clicked');
        }
      }, {
        text: 'Alterar nome do grupo1',
        handler: () => {
          console.log('Alterar nome do grupo');
          this.openChangeGroupName()
        }
      }, {
        text: 'Apagar o grupo',
        handler: () => {
          console.log('Play clicked');
        }
      },
      ]
    });
    await actionSheet.present();
  }
 */

  async _openChatOptions() {

    const enterAnimation = (baseEl: any) => {
      const backdropAnimation = this.animationController.create()
        .addElement(baseEl.querySelector('ion-backdrop')!)
        .fromTo('opacity', '0.01', 'var(--backdrop-opacity)');

      const wrapperAnimation = this.animationController.create()
        .addElement(baseEl.querySelector('.modal-wrapper')!)
        .keyframes([
          { offset: 0, opacity: '1', right: '-100%' },
          { offset: 1, opacity: '1', right: '0px' }
        ]);

      return this.animationController.create()
        .addElement(baseEl)
        .easing('ease-out')
        .duration(5000)
        .addAnimation([backdropAnimation, wrapperAnimation]);
    }

    const leaveAnimation = (baseEl: any) => {
      return enterAnimation(baseEl).direction('reverse');
    }

    const modal = await this.modalController.create({
      enterAnimation,
      leaveAnimation,
      component: ChatOptionsFeaturesPage,
      cssClass: 'model profile-modal search-submodal',
      componentProps: {
        roomId: this.roomId,
        members: this.members,
      }
    });

    await modal.present();
    modal.onDidDismiss().then((res)=>{
      console.log(res['data']);
      if(res['data'] == 'meeting'){
        //this.closeAllDesktopComponents.emit();
        let data = {
          roomId: this.roomId,
          members: this.members
        }
        this.openNewEventPage.emit(data);
      }

    });
  }

  async serverLongPull(){
    this.chatService.getPrivateGroupMessages(this.roomId).subscribe(async res => {

    if (res == 502) {
      // Connection timeout
      // happens when the connection was pending for too long
      // let's reconnect
      await this.serverLongPull();
    } else if (res != 200) {
      // Show Error
      //showMessage(response.statusText);
      //this.loadMessages()
      let msgOnly = res['messages'].filter(data => data.t != 'au');
      this.messages = msgOnly.reverse();
      console.log(this.messages);
      // Reconnect in one second
      if(this.route.url != "/home/chat"){
        console.log("Timer message stop")
      } else {
        if(document.querySelector('app-group-messages')){
          await new Promise(resolve => setTimeout(resolve, 5000));
          await this.serverLongPull();
          console.log('Timer message running')
        }
        else{

        }
      }

    } else {
      // Got message
      //let message = await response.text();
      //this.loadMessages()
      await this.serverLongPull();
    }
  });
  }

}

