import { AfterViewChecked, AfterViewInit, Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router'
import { ModalController, NavParams, PopoverController } from '@ionic/angular';
import { ContactsPage } from 'src/app/pages/chat/messages/contacts/contacts.page';
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 { connection } from 'src/app/services/socket/synchro.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 { 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, AfterViewInit, OnDestroy {
  showLoader: boolean;

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

  loggedUser: any;

  message = '';
  messages:any;
  userPresence='';
  dmUsers:any;
  roomId:string;
  el:any;
  members:any;
  scrollingOnce:boolean = true;

  connection  = connection;
  chatMessageStore = ChatMessageStore
  chatUserStorage = ChatUserStorage

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

  constructor(
    public popoverController: PopoverController,
    private modalController: ModalController,
    private navParams: NavParams,
    private chatService: ChatService,
    private authService: AuthService,
    private alertService: AlertService,
    private toastService: ToastService,
    private route: Router,
    private activatedRoute: ActivatedRoute,
  ) {
    /* this.activatedRoute.paramMap.subscribe(params => {
      if(params["params"].SerialNumber) {
        this.roomId = params["params"].roomId;
      }
    }); */
    this.loggedUser = authService.ValidatedUserChat['data'];
    this.roomId = this.navParams.get('roomId');
  }

  ngOnInit() {

    /* setInterval(()=>{ */
      this.load();
    /* }, 9000); */
    /* this.el = document.getElementById("scrollToBottom");
    this.el.scrollTop = this.el.scrollHeight - this.el.scrollTop; */

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

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

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



  sendMessage() {
    let body = {
      "message":
      {
        "rid": this.roomId, "msg": this.message
      }
    }
    this.chatService.sendMessage(body).subscribe(res=> {
      //this.loadMessages();
      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.showLoader = false;
    })
  }
  getChatMembers() {
    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;
    });
  }

  showDateDuration(start:any){
    let end;
    end = new Date();
    start = new Date(start);
    let customizedDate;

    const totalSeconds     = Math.floor((end - (start))/1000);;
    const totalMinutes     = Math.floor(totalSeconds/60);
    const totalHours       = Math.floor(totalMinutes/60);
    const totalDays        = Math.floor(totalHours/24);

    const hours   = totalHours - ( totalDays * 24 );
    const minutes = totalMinutes - ( totalDays * 24 * 60 ) - ( hours * 60 );
    const seconds = totalSeconds - ( totalDays * 24 * 60 * 60 ) - ( hours * 60 * 60 ) - ( minutes * 60 );

    if(totalDays == 0){
      if(start.getDate() == new Date().getDate()){
        let time = start.getHours() + ":" + this.addZero(start.getUTCMinutes());
        return time;
      }
      else{
        return 'Ontem';
      }
    }
    else{
      let date = start.getDate() + "/" + (start.getMonth()+1) + "/" + start.getFullYear();
      return date;
    }
  }

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

  async openMessagesOptions(ev?: any) {
    const popover = await this.popoverController.create({
      component: MessagesOptionsPage,
      componentProps: {
        roomId: this.roomId,
      },
      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();
  }

  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.roomId,
        members: this.members,
        eventSelectedDate: new Date(),
      },
      translucent: true
    });
    return await popover.present();
  }

  async serverLongPull() {

    const roomId = this.roomId
    this.chatService.getRoomMessages(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 {
        //Check if modal is opened
        if(document.querySelector('.isMessagesChatOpened')){
          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();
    }
    });
  }

}
