import { AfterViewChecked, AfterViewInit, Component, ElementRef, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges, ViewChild } from '@angular/core';
import { AnimationController, 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 { ToastService } from 'src/app/services/toast.service';
import { ChatOptionsPopoverPage } from 'src/app/shared/popover/chat-options-popover/chat-options-popover.page';
import { MessagesOptionsPage } from 'src/app/shared/popover/messages-options/messages-options.page';
import { ContactsPage } from '../new-group/contacts/contacts.page';
import { Router } from '@angular/router';
import { connection } from 'src/app/services/socket/synchro.service';
import { ChatOptionsFeaturesPage } from 'src/app/modals/chat-options-features/chat-options-features.page';
import { ChatMessageStore } from 'src/app/store/chat/chat-message.service';
import { ChatUserStorage } from 'src/app/store/chat/chat-user.service';

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

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

  loggedUser: any;

  message = '';
  messages:any;
  dm:any;
  userPresence='';
  dmUsers:any;
  checktimeOut: boolean;
  members:any;

  @Input() roomId:string;
  @Input() showMessages:string;

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


  connection  = connection;
  chatMessageStore = ChatMessageStore
  chatUserStorage = ChatUserStorage

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

  constructor(
    public popoverController: PopoverController,
    private modalController: ModalController,
    /* private navParams: NavParams, */
    private chatService: ChatService,
    private authService: AuthService,
    private animationController: AnimationController,
    private alertService: AlertService,
    private toastService: ToastService,
    private route: Router
  ) {
    this.loggedUser = authService.ValidatedUserChat['data'];

   /*  this.dm = this.navParams.get('dm'); */
  }
  ngOnChanges(changes: SimpleChanges): void {
    this.load();

    //throw new Error('Method not implemented.');
  }

  ngOnInit() {

    this.scrollToBottom();

    /* setInterval(()=>{ */
      this.load();
    /* }, 9000); */
    console.log(this.roomId);
    console.log("Chat route", this.route.url)

    this.setStatus('online');
  }

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

  notImplemented(){
    this.alertService.presentAlert('Funcionalidade em desenvolvimento');
  }

  load = ()=>{
    this.checktimeOut = true;
    this.serverLongPull();
    this.getChatMembers();
  }


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

  scrollToBottom(): void {
    try {
      if(this.scrollingOnce){
        this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
        //this.scrollingOnce = false;
      }
    } 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.checktimeOut = false;
    this.setStatus('away');
    window.removeEventListener('scroll', this.scrollChangeCallback, true);
  }

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

  sendMessage() {

    this.connection.$send({})

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

    this.chatService.sendMessage(body).subscribe(res=> {
      this.scrollingOnce = true;
    });
    this.message = "";
  }

  loadMessages(){
    //this.showLoader = true;
    const roomId = this.roomId
    this.chatService.getRoomMessages(this.roomId).subscribe(res => {
      console.log(res);
      this.messages = res['messages'].reverse();
      this.chatMessageStore.add(roomId, this.messages)

      console.log(this.messages);
      //this.serverLongPull(res)
      /* this.chatService.subscribe(this.roomId).then(res => {
        console.log("Real fake msg", res)
      }); */
      //this.showLoader = false;
    })
  }

  getChatMembers() {
    console.log(this.roomId);

    //this.showLoader = true;
    this.chatService.getMembers(this.roomId).subscribe(res=> {
      this.members = res['members'];
      this.dmUsers = res['members'].filter(data => data.username != this.loggedUser.me.username)
      console.log(res);
      console.log(this.dmUsers);
      this.showLoader = false;
    });
  }

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

  async addContacts(){
    const modal = await this.modalController.create({
      component: ContactsPage,
      componentProps: {},
      cssClass: 'contacts',
      backdropDismiss: false
    });

    await modal.present();

    modal.onDidDismiss();
  }

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

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



  async _openMessagesOptions() {

    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: MessagesOptionsPage,
      cssClass: 'model profile-modal search-submodal',
      componentProps: {
        roomId: this.roomId,
      }
    });
    return await modal.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(500)
        .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() {

    const roomId = this.roomId
    this.chatService.getRoomMessages(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()
      this.messages = res['messages'].reverse();
      this.chatMessageStore.add(roomId, this.messages)
      console.log(this.messages);
      // Reconnect in one second
      if(this.route.url != "/home/chat"){
        console.log("Timer message stop")
      } else {
          if(document.querySelector('app-messages')){
            await new Promise(resolve => setTimeout(resolve, 5000));
            await this.serverLongPull();
            console.log('Timer message running')
          }
      }
    } else {
      // Got message
      //let message = await response.text();
      //this.loadMessages()
      await this.serverLongPull();
    }
  });
  }

}

