import { AfterViewChecked, AfterViewInit, Component, ElementRef,ChangeDetectorRef, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges, ViewChild } from '@angular/core';
import { AnimationController, GestureController, IonSlides, 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 { 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';
import { TimeService } from 'src/app/services/functions/time.service';
import { FileService } from 'src/app/services/functions/file.service';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { ViewDocumentPage } from 'src/app/modals/view-document/view-document.page';
import { ThemeService } from 'src/app/services/theme.service'
import { PreviewCameraPage } from 'src/app/modals/preview-camera/preview-camera.page';
import { ViewMediaPage } from 'src/app/modals/view-media/view-media.page';
import { ViewEventPage } from 'src/app/modals/view-event/view-event.page';

@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;
  @ViewChild('message-item') messageContainer: 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>();
  @Output() getDirectMessages:EventEmitter<any> = new EventEmitter<any>();


  chatMessageStore = ChatMessageStore
  chatUserStorage = ChatUserStorage

  scrollingOnce:boolean = true;
  private scrollChangeCallback: () => void;
  currentPosition: any;
  startPosition: number;
  mesageItemDropdownOptions: boolean = false;
  scrollToBottomBtn = false;
  longPressActive = false;
  frameUrl: any;

  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,
    private timeService: TimeService,
    private fileService: FileService,
    private gestureController: GestureController,
    private http:HttpClient,
    public ThemeService: ThemeService,
    private changeDetectorRef: ChangeDetectorRef,
    private router: 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');
  }

  onPressingMessage(){
    const gesture = this.gestureController.create({
      el: this.messageContainer.nativeElement,
      gestureName: 'long-press',
      onStart: ev =>{
        this.longPressActive = true;
        console.log('Pressing');
      },
      onEnd: ev => {
        this.longPressActive = false;
        console.log('Stop pressing');
      }
    });
  }

  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) { }
  }

  scrollToBottomClicked(): void {
    try {
      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;
    let windowHeight = e.srcElement.scrollHeight;
    let containerHeight = windowHeight - e.srcElement.clientHeight;

    if (scroll > this.currentPosition) {
      //alert('BOTTOM');
    } else {
      //alert('UP');
      this.scrollingOnce = false;
    }
    if((containerHeight - 100) > scroll){
      this.scrollToBottomBtn = true;
    }
    else{
      this.scrollToBottomBtn = 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);
  }

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

  async goToEvent(eventId: any) {
    let classs;
    if (window.innerWidth < 701) {
      classs = 'modal modal-desktop'
    } else {
      classs = 'modal modal-desktop showAsideOptions'
    }
    const modal = await this.modalController.create({
      component: ViewEventPage,
      componentProps: {
        eventId: eventId,
      },
      cssClass: classs,
    });
    await modal.present();
    modal.onDidDismiss().then((res) => {
      console.log(res);
    });
  }

  sendMessage() {
    let body = {
      "message":
      {
        "rid": this.roomId, "msg": this.message,
      }
    }
    this.chatService.sendMessage(body).subscribe(res=> {
      this.scrollingOnce = true;
    });
    this.message = "";
  }

  deleteMessage(msgId:string){
    let body = {
      "roomId": this.roomId,
      "msgId": msgId,
      "asUser": false,
    }
    this.alertService.confirmDeleteMessage(body);
    /* this.chatService.deleteMessage(body).subscribe(res=>{
      console.log(res);
    }); */
  }

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

  async viewDocument(msg:any, url?:string){
    if(msg.file.type == "application/img"){
      let response:any = await this.fileService.getFile(msg.file.guid).toPromise();
      console.log(response);
      alert(response);

      //this.openPreview(msg);

    }
    else if(msg.file.type == "application/webtrix") {
       this.openViewDocumentModal(msg.file);
     }
     else{
       let fullUrl;
       fullUrl = "https://www.tabularium.pt" + url;
       //fullUrl = "http://www.africau.edu/images/default/sample.pdf";

       this.frameUrl = fullUrl;
       //this.fileService.viewDocumentByUrl(fullUrl);
       this.chatService.getDocumentDetails(fullUrl);
     }
  }


  async openViewDocumentModal(file:any){
    let task = {
      serialNumber: '',
      taskStartDate: '',
      isEvent: true,
      workflowInstanceDataFields: {
        FolderID: '',
        Subject: file.Assunto,
        SourceSecFsID: file.ApplicationId,
        SourceType: 'DOC',
        SourceID: file.DocId,
        DispatchNumber: ''
      }
    }

    let doc = {
        "Id": "",
        "ParentId": "",
        "Source": 1,
        "ApplicationId": file.ApplicationId,
        "CreateDate": "",
        "Data": null,
        "Description":"",
        "Link": null,
        "SourceId": file.DocId,
        "SourceName": file.Assunto,
        "Stakeholders": "",
    }

    const modal = await this.modalController.create({
      component: ViewDocumentPage,
      componentProps: {
        trustedUrl: '',
        file: {
          title: file.Assunto,
          url: '',
          title_link: '',
        },
        Document: doc,
        applicationId: file.ApplicationId,
        docId: file.DocId,
        folderId: '',
        task: task
      },
      cssClass: 'modal modal-desktop'
    });
    await modal.present();
  }

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



  takePicture(){
    const roomId = this.roomId
    this.fileService.addCameraPictureToChat(roomId);
  }
  addImage(){
    const roomId = this.roomId;
    this.fileService.addPictureToChat(roomId);
    //this.fileService.loadPicture();
    //this.fileService.addPictureToChat(roomId);
  }
  addFile(){
    this.fileService.addDocumentToChat(this.roomId);
  }
  addFileWebtrix(){
    this.fileService.addDocGestaoDocumentalToChat(this.roomId);
  }
  bookMeeting(){
    let data = {
      roomId: this.roomId,
      members: this.members
    }
    this.openNewEventPage.emit(data);
  }


  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);
      }
      else if(res['data'] == 'take-picture'){
        this.fileService.addCameraPictureToChat(this.roomId);
        //this.loadPicture();
      }
      else if(res['data'] == 'add-picture'){
        this.fileService.addPictureToChat(this.roomId);
        //this.loadPicture();
      }
      else if(res['data'] == 'add-document'){
        this.fileService.addDocumentToChat(this.roomId);
        //this.loadDocument();
      }
      else if(res['data'] == 'documentoGestaoDocumental'){

        this.fileService.addDocGestaoDocumentalToChat(this.roomId);
        this.showLoader = false;
        //this.addDocGestaoDocumental();
      }
      this.loadMessages();

    });
  }

  async serverLongPull() {

    const roomId = this.roomId;

    this.chatService.getRoomMessages(this.roomId).subscribe(async res => {
      //console.log(res['success']);


     if (res['success'] == true) {
      // 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();
          this.getDirectMessages.emit();
          console.log('Timer message running')
        }
      }
    } /* else {
      // Got message
      //let message = await response.text();
      //this.loadMessages()
      await this.serverLongPull();
    } */
  }, (error)=>{
    console.log(error);
    this.serverLongPull();

  });
  }sliderOpts = {
    zoom: false,
    slidesPerView: 1.5,
    spaceBetween: 20,
    centeredSlides: true
  };
  zoomActive = false;
zoomScale = 1;

sliderZoomOpts = {
  allowSlidePrev: false,
  allowSlideNext: false,
  zoom: {
    maxRatio: 5
  },
  on: {
    zoomChange: (scale, imageEl, slideEl) => {
      this.zoomActive = true;
      this.zoomScale = scale/5;
      this.changeDetectorRef.detectChanges();
    }
  }
}

async touchEnd(zoomslides: IonSlides, card) {
  // Zoom back to normal
  const slider = await zoomslides.getSwiper();
  const zoom = slider.zoom;
  zoom.out();

  // Card back to normal
  card.el.style['z-index'] = 9;

  this.zoomActive = false;
  this.changeDetectorRef.detectChanges();
}

touchStart(card) {
  // Make card appear above backdrop
  card.el.style['z-index'] = 11;
}

  async openPreview(msg) {
    const modal = await this.modalController.create({
      component:  ViewMediaPage,
      cssClass: 'modal modal-desktop',
      componentProps: {
        image: msg.attachments[0].image_url,
        username: msg.u.name,
        _updatedAt: msg._updatedAt
      }
    });
    modal.present();
  }
}



