import { Component, ElementRef, OnInit, ViewChild, AfterViewChecked, AfterViewInit, OnDestroy, ChangeDetectorRef, } from '@angular/core';
import { ActionSheetController, IonSlides, MenuController, ModalController, NavParams, 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 { ChatOptionsPopoverPage } from 'src/app/shared/popover/chat-options-popover/chat-options-popover.page';
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 { EditGroupPage } from '../edit-group/edit-group.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 { FileService } from 'src/app/services/functions/file.service';
import { ToastService } from 'src/app/services/toast.service';
import { environment } from 'src/environments/environment';
import { NewEventPage } from '../../agenda/new-event/new-event.page';
import { EventPerson } from 'src/app/models/eventperson.model';
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-group-messages',
  templateUrl: './group-messages.page.html',
  styleUrls: ['./group-messages.page.scss'],
})
export class GroupMessagesPage implements OnInit, AfterViewInit, OnDestroy {



  showLoader: boolean;
  isGroupCreated:boolean;
  loggedUser: any;
  message:any;
  messages:any;

  room:any;
  roomName:any;
  members:any;
  contacts: string[] = [" Ana M.", "Andre F.", "Bruno G.", "Catarina T", "Tiago"];
  allUsers:any[] = [];

  roomId: string;
  loggedUserChat:any;
  eventSelectedDate: Date = new Date();

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

  capturedImage:any;
  capturedImageTitle:any;
  attendees: EventPerson[] = [];
  scrollToBottomBtn = false;

  longPressActive = false;
  showMessageOptions = false;
  selectedMsgId:string;
  roomCountDownDate:any;

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

  constructor(
    private menu: MenuController,
    private modalController: ModalController,
    private actionSheetController: ActionSheetController,
    public popoverController: PopoverController,
    private chatService: ChatService,
    private navParams: NavParams,
    private authService: AuthService,
    private alertService: AlertService,
    private route: Router,
    private timeService: TimeService,
    private fileLoaderService: FileLoaderService,
    private fileToBase64Service: FileToBase64Service,
    private fileService: FileService,
    private toastService: ToastService,
    public ThemeService: ThemeService,
    private changeDetectorRef: ChangeDetectorRef
  ) {
    this.loggedUserChat = authService.ValidatedUserChat['data'];
    this.isGroupCreated = true;
    this.roomId = this.navParams.get('roomId');
    window.onresize = (event) => {
      if( window.innerWidth > 701){
        this.modalController.dismiss();
      }
    };
  }

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

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

  deleteMessage(msgId:string){
    let body = {
      "roomId": this.roomId,
      "msgId": msgId,
      "asUser": false,
    }
    if(msgId){
      this.alertService.confirmDeleteMessage(body);
    }
    else{
      this.toastService.badRequest('Não foi possível apagar');
    }
    this.showMessageOptions = false;
    this.selectedMsgId = "";
  }

  ngAfterViewInit() {
    this.scrollChangeCallback = () => this.onContentScrolled(event);
    window.addEventListener('scroll', this.scrollChangeCallback, true);
    this.roomCountDownDate = this.timeService.countDownDate(this.room.customFields.countDownDate, this.room._id);
  }

  handlePress(id?:string){
    this.selectedMsgId = id;
    this.showMessageOptions = true;
  }

  handleClick(){
    this.showMessageOptions = false;
    this.selectedMsgId = "";
  }

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

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

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

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

  getRoomInfo(){
    this.showLoader = true;
    this.chatService.getRoomInfo(this.roomId).subscribe(room=>{
      this.room = room['room'];
      this.roomName = this.room.name.split('-').join(' ');
      if(this.room.customFields.countDownDate){
        this.roomCountDownDate = this.timeService.countDownDateTimer(this.room.customFields.countDownDate, this.room._id);
      }
      this.getGroupContacts(this.room);
      this.loadGroupMessages(this.room);
      this.showLoader = false;
    });
  }

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

  /* load(){
    this.getGroupContacts();
    this.loadGroupMessages();
  } */

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

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

  getGroupContacts(room:any){
    this.showLoader = true;
    //If group is private call getGroupMembers
    if(this.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(room:any){
    this.showLoader = true;
    //If group is private call getGroupMembers
    if(this.room.t === 'p'){
      this.chatService.getPrivateGroupMessages(this.roomId).subscribe(res=>{
        console.log(res);
        let msgOnly = res['messages'].filter(data => data.t != 'au');
        this.messages = msgOnly.reverse();
        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();
      });
    } */
  }

  showDateDuration(start:any){
    return this.timeService.showDateDuration(start);
  }
  countDownDate(date:any, roomId:string){
    this.roomCountDownDate = this.timeService.countDownDate(date, roomId);
    return this.timeService.countDownDateTimer(date, roomId);
  }

  addZero(i) {
    if (i < 10) {
      i = "0" + i;
    }
    return i;
  }




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

    this.chatService.sendMessage(body).subscribe(res=> {
      this.getRoomInfo();
      this.scrollingOnce = true;

    },(error) => {

    });
    this.message = "";
  }

  async openOptions() {
    const modal = await this.popoverController.create({
      component: ChatPopoverPage,
      cssClass: 'chat-popover',
      componentProps: {
        roomId: this.roomId,
      },
    });
    await modal.present();
    modal.onDidDismiss().then(res=>{
      if(res.data == 'leave'){
        console.log('saiu do grupo');
      }
      else if(res.data == 'cancel'){
        console.log('cancel');
      }
      else if(res.data == 'edit'){
        this.editGroup(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)
    };
  }

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

  }

  async bookMeeting() {
    this.attendees = this.members.map((val)=>{
      return {
        Name: val.name,
        EmailAddress: val.username+"@"+environment.domain,
        IsRequired: "true",
      }
    });
    console.log(this.attendees);
    this.popoverController.dismiss();
    if( window.innerWidth <= 1024){
      const modal = await this.modalController.create({
        component: NewEventPage,
        componentProps:{
          attendees: this.attendees,
        },
        cssClass: 'modal  modal-desktop',
        backdropDismiss: false
      });
      await modal.present();
      modal.onDidDismiss().then((data) => {
        if(data){

        }
      });
    }
  }

  async openChatOptions(ev?: any) {
    console.log(this.members);

    const popover = await this.popoverController.create({
      component: ChatOptionsPopoverPage,
      cssClass: 'chat-options-popover',
      event: ev,
      componentProps: {
        room: this.room,
        members: this.members,
        eventSelectedDate: new Date(),
      },
      translucent: true
    });
    await popover.present();
    await popover.onDidDismiss().then((res)=>{
      console.log(res['data']);
      if(res['data'] == 'meeting'){
        this.bookMeeting();
      }
      else if(res['data'] == 'take-picture'){
        this.fileService.addCameraPictureToChat(this.roomId);
        //this.loadPicture();
      }
      else if(res['data'] == 'add-picture'){
        this.fileService.addPictureToChatMobile(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.addDocGestaoDocumental();
      }
      this.loadGroupMessages(this.roomId);
    });
  }

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

  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.getRoomInfo();
      //this.modalController.dismiss(res.data);
    });
  }

  /* 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 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 {
        //Check if modal is opened
        if(document.querySelector('.isGroupChatOpened')){
          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();
    }
  });
  }

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

