import { Component, OnChanges, OnInit, Input, SimpleChanges,ChangeDetectorRef,Output, EventEmitter, ViewChild, ElementRef, AfterViewChecked, AfterViewInit, OnDestroy} from '@angular/core';
import { ActionSheetController, AnimationController, IonSlides, 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';
import { TimeService } from 'src/app/services/functions/time.service';
import { FileLoaderService } from 'src/app/services/file/file-loader.service';
import { FileToBase64Service } from 'src/app/services/file/file-to-base64.service';
import { SearchPage } from 'src/app/pages/search/search.page';
import { SearchList } from 'src/app/models/search-document';
import { ProcessesService } from 'src/app/services/processes.service';
import { FileService } from 'src/app/services/functions/file.service';
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';

/*
import * as pdfjsLib from 'pdfjs-dist';
if( pdfjsLib !== undefined ){
  console.log( "set worker...");
   pdfjsLib.GlobalWorkerOptions.workerSrc = "https://npmcdn.com/pdfjs-dist@2.4.456/build/pdf.worker.js";
}
*/

@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;
  messages:any;
  allUsers:any[] = [];
  documents:SearchList[] = [];


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

  capturedImage:any;
  capturedImageTitle:any;

  loggedUserChat:any;
  scrollingOnce:boolean = true;
  private scrollChangeCallback: () => void;
  currentPosition: any;
  startPosition: number;
  scrollToBottomBtn = false;
  roomCountDownDate:string;
  roomCountDownTime:string;

  @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>();
  @Output() getGroups:EventEmitter<any> = new EventEmitter<any>();

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

  pdfurl = "http://www.africau.edu/images/default/sample.pdf";

  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,
    private timeService: TimeService,
    private fileLoaderService: FileLoaderService,
    private fileToBase64Service: FileToBase64Service,
    private processesService: ProcessesService,
    private fileService: FileService,
    public ThemeService: ThemeService,
    private changeDetectorRef: ChangeDetectorRef
  ) {
    this.loggedUserChat = authService.ValidatedUserChat['data'];
    this.isGroupCreated = true;
    this.roomCountDownDate = "";
    this.roomCountDownTime = "";

  }
  ngOnChanges(changes: SimpleChanges): void {
    this.getRoomInfo();
    //this.scrollToBottom();
  }

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

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

  countDownDate(){
    //this.roomCountDownTime = this.timeService.countDownDateTimer(this.roomCountDownDate, this.room._id);
    return this.timeService.countDownDateTimer(this.roomCountDownDate, this.roomId);
  }

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

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

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

  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.setStatus('away');
    window.removeEventListener('scroll', this.scrollChangeCallback, true);
  }

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

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

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

  async getRoomInfo(){
    let room = await this.chatService.getRoomInfo(this.roomId).toPromise();
    this.room=room['room'];
    if(this.room.name){
      this.roomName = this.room.name.split('-').join(' ');
    }

    if(this.room.customFields.countDownDate){
      this.roomCountDownDate = this.room.customFields.countDownDate;
    }

    this.getGroupContacts(this.room);
  }

  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,
        /* "attachments": [{
          "color": "#ff0000",
          "text": "Yay for gruggy!",
          "title": "Attachment Example",
          "title_link": "https://youtube.com",
          "title_link_download": false,
          "image_url": "https://upload.wikimedia.org/wikipedia/commons/e/ee/Chain_link_icon.png",
        }] */
      }
    }

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

  deleteMessage(msgId:string){
    let body = {
      "roomId": this.roomId,
      "msgId": msgId,
      "asUser": false,
    }
    this.alertService.confirmDeleteMessage(body);
  }

  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.getRoomInfo();
        this.closeAllDesktopComponents.emit();
        this.showEmptyContainer.emit();
      }
      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
    });
    await popover.present();
    await popover.onDidDismiss().then(()=>{
    });
  }
  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)
    });
  }

  loadPicture() {
    const input = this.fileLoaderService.createInput({
      accept: ['image/apng', 'image/jpeg', 'image/png']
    })

    input.onchange = async () => {
      const file = this.fileLoaderService.getFirstFile(input)

      console.log(file);

      const imageData =  await this.fileToBase64Service.convert(file)
      this.capturedImage = imageData;
      this.capturedImageTitle = file.name;

      let body = {
        "message":
        {
          "rid": this.roomId,
          "msg": "",
          "attachments": [{
            //"title": this.capturedImageTitle ,
            //"text": "description",
            "title_link_download": false,
            "image_url": this.capturedImage,
          }]
        }
      }

      this.chatService.sendMessage(body).subscribe(res=> {
        console.log(res);
      },(error) => {

      });
      //console.log(this.capturedImage)
    };
  }

  loadDocument() {
    const input = this.fileLoaderService.createInput({
      accept: ['.doc', '.docx', '.pdf']
    })

    input.onchange = async () => {
      const file = this.fileLoaderService.getFirstFile(input)

      console.log(file);

      const imageData =  await this.fileToBase64Service.convert(file)
      this.capturedImage = imageData;
      this.capturedImageTitle = file.name;

      let body = {
        "message":
        {
          "rid": this.roomId,
          "msg": "",
          "attachments": [{
            "title": this.capturedImageTitle,
            "text": "",
            "title_link": this.capturedImage,
            "title_link_download": true,
            "thumb_url": "https://static.ichimura.ed.jp/uploads/2017/10/pdf-icon.png",
            "message_link": this.capturedImage,
          }],
          "file":{
            "name": this.capturedImageTitle,
            "type": "application/pdf",
          }
        }
      }

      this.chatService.sendMessage(body).subscribe(res=> {
        //console.log(res);
      },(error) => {

      });
      //console.log(this.capturedImage)
    };
  }

  async addDocGestaoDocumental(){
    const modal = await this.modalController.create({
      component: SearchPage,
      cssClass: 'group-messages modal-desktop search-modal search-modal-to-desktop',
      componentProps: {
        type: 'AccoesPresidenciais & ArquivoDespachoElect',
        select: true,
        showSearchInput: true,
      }
    });
    await modal.present();
    modal.onDidDismiss().then(async res=>{
      if(res){
        const data = res.data;
        this.documents.push(data.selected);
        console.log(res.data.selected);
        console.log(res.data.selected.Id);
        console.log(res.data.selected.ApplicationType);

        let url = await this.processesService.GetDocumentUrl(res.data.selected.Id, res.data.selected.ApplicationType).toPromise();
        let url_no_options: string = url.replace("webTRIX.Viewer","webTRIX.Viewer.Branch1");
        console.log(url_no_options);
        //console.log('Oie');

        let body = {
          "message":
          {
            "rid": this.roomId,
            "msg": "",
            "attachments": [{
              "title": res.data.selected.Assunto,
              "text": res.data.selected.DocTypeDesc,
              "title_link": url_no_options,
              "title_link_download": true,
              "thumb_url": "https://static.ichimura.ed.jp/uploads/2017/10/pdf-icon.png",
              "message_link": url_no_options,
            }]
          }
        }
        this.chatService.sendMessage(body).subscribe(res=> {
          console.log(res);
        },(error) => {

        });

      }
    });
  }

  viewDocument(file:any, url?:string){
    if(file.type == "application/webtrix") {
       this.openViewDocumentModal(file);
     }
     else{
       let fullUrl = "https://www.tabularium.pt" + url;
       this.fileService.viewDocumentByUrl(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();
  }

  takePicture(){
    this.fileService.addCameraPictureToChat(this.roomId);
  }
  addImage(){
    this.fileService.addPictureToChat(this.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(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);
      }
      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.loadDocument();
      }
      else if(res['data'] == 'documentoGestaoDocumental'){
        this.fileService.addDocGestaoDocumentalToChat(this.roomId);
        //this.addDocGestaoDocumental();
      }
      this.loadGroupMessages(this.roomId);

    });
  }

  async serverLongPull(){

    if(this.route.url != "/home/chat" && document.querySelector('app-group-messages')){
      console.log("Timer message stop")
    }
    else
    {

      this.chatService.getPrivateGroupMessages(this.roomId).subscribe(async res =>
      {
        if(res['success'] == true) {
          // 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(document.querySelector('app-group-messages')){
              await new Promise(resolve => setTimeout(resolve,5000));
              this.getGroups.emit();
              console.log('Timer message running')
              await this.serverLongPull();
          }

        }
        else {
          alert('HEY2')
          // 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();
}

}

