/* eslint-disable */
/* tslint:disable */
import { Component, OnInit } from '@angular/core';
import { Event } from '../models/event.model';
import { NotificationsService } from '../services/notifications.service';
/*import { WebNotificationsService } from '../services/webnotifications.service'; */
import { AlertController, Platform } from '@ionic/angular';
import { Router, ActivatedRoute } from '@angular/router';
import { ToDayEventStorage } from '../store/to-day-event-storage.service';
import { TotalDocumentStore } from '../store/total-document.service';
import { DespachoService } from '../Rules/despacho.service';
import { ExpedienteGdStore } from '../store/expedientegd-store.service';
import { InativityService } from '../services/inativity.service';
import { SessionStore } from '../store/session.service';
import { StorageService } from '../services/storage.service';
import { File } from '@ionic-native/file/ngx';
/* import { WebNotificationPopupService } from '../services/notification/web-notification-popup.service'; */
import { DocumentCounterService } from '../services/worker/document-counter.service';
import { PermissionService } from '../services/worker/permission.service';
import { Network } from '@ionic-native/network/ngx';
import { BackgroundService } from 'src/app/services/background.service';
import { OfflineManagerService } from 'src/app/services/offline-manager.service';
import { Storage } from '@ionic/storage';
import { EventsService } from 'src/app/services/events.service';
import { ProcessesService } from 'src/app/services/processes.service';
import { ScreenOrientation } from '@ionic-native/screen-orientation/ngx';
import { SqliteService } from 'src/app/services/sqlite.service';
import { Device } from '@capacitor/device';
import { RouteService } from 'src/app/services/route.service';
import { RocketChatClientService } from 'src/app/services/socket/rocket-chat-client.service';
import { environment } from 'src/environments/environment';
import { v4 as uuidv4 } from 'uuid'
import { RealTimeAPI } from "rocket.chat.realtime.api.rxjs";

@Component({
  selector: 'app-home',
  templateUrl: './home.page.html',
  styleUrls: ['./home.page.scss'],
})
export class HomePage implements OnInit {
  eventsList: Event[];
  prEventList: Event[];
  mdEventList: Event[];

  totalEvent = 0;
  totalExpediente = 0;
  profile: string;

  toDayEventStorage = ToDayEventStorage
  totalDocumentStore = TotalDocumentStore
  expedienteGdStore = ExpedienteGdStore

  adding: "intervenient" | "CC" = "intervenient";
  mobileComponent = {
    showAddNewEvent: false,
    showEditEvent: false,
    showEventDetails: false,
    showEventList: false,
    transparentEventList: false,
    transparentEventToApprove: false,
    showEventToApprove: false,
    showAttendees: false,
    showAttendeeModal: false
  }
  eventToaprove: any = {
    back: false,
    serialNumber: "",
    saveData: {}
  }
  selectedEvent: Event;
  postEvent: any;
  folderId: string;

  status: string = "";
  audioName: string = "";

  RocketChatClientService = RocketChatClientService

  constructor(
    private router: Router,
    public modalCtrl: AlertController,
    private notificationsService: NotificationsService,
    private platform: Platform,
    private activeroute: ActivatedRoute,
    /* private webnotification: WebNotificationsService, */
    public p: PermissionService,
    public documentCounterService: DocumentCounterService,
    private despachoRule: DespachoService,
    private inativityService: InativityService,
    private storageService: StorageService,
    /* private webNotificationPopupService: WebNotificationPopupService, */
    private backgroundservice: BackgroundService,
    private offlinemanager: OfflineManagerService,
    private storage: Storage,
    private eventservice: EventsService,
    private processservice: ProcessesService,
    private screenOrientation: ScreenOrientation,
    private sqliteservice: SqliteService,
    private RouteService: RouteService) {

    this.RocketChatClientService.connect(()=>{

      this.RocketChatClientService.login({
        username: 'paulo.pinto',
        email: 'paulo.pinto@gabinetedigital.local',
        password: 'tabteste@006'
      }).then((message)=>{
        // alert('login')
        console.log('rocket chat login successfully', message)
        this.RocketChatClientService.getRooms().then((rooms: any)=>{
          console.log('rooms', rooms)

          rooms.result.update.forEach((room:any) => {
            console.log('room', room)
            this.RocketChatClientService.subscribe(room.lastMessage.rid).then((subscription)=>{
              console.log('subscription', subscription)
            })
          });

        })


        //send message                              // roomId                // Message

        this.RocketChatClientService.send('fsMwcNdufWvdnChj7ya9nF9cX2HizxxWAM', 'Mensagem enviada programaticamente.'+ new Date().toISOString())
      }).catch((message)=>{
        console.log('rocket chat login failed', message)
      }).finally(()=>{
      })  

    })
    
    // this.RocketChatClientService.send()
    /* this.webNotificationPopupService.askNotificationPermission() */

    this.router.events.subscribe((val) => {
      document.querySelectorAll('ion-modal').forEach((e: any) => e.remove())
      document.querySelectorAll('popover-viewport').forEach((e: any) => e.remove())
    });

    window['platform'] = platform

    window['inactivity/function'] = () => {

      if (window.location.pathname != '/inactivity') {

        document.querySelectorAll('ion-modal').forEach((e: any) => e.remove())
        document.querySelectorAll('.popover-viewport').forEach((e: any) => e.remove())

        const pathname = window.location.pathname
        SessionStore.setUrlBeforeInactivity(pathname)
        this.router.navigate(['/inactivity']);
      }
    }



  }

  goto(url) {
    this.router.navigate([url])
  }

  refreshing() { }

  ngOnInit() {

    this.logDeviceInfo();

    this.notificationsService.onReciveForeground();
    this.notificationsService.onReciveBackground();

    window.addEventListener('online', () => {
      console.log('Became online')
      this.backgroundservice.online()
      if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
      } else {
        this.synchWhenOnline()
      }
    });
    window.addEventListener('offline', () => {
      console.log('Became offline')
      this.backgroundservice.offline()
    });

    this.updateList()

    /* var myWorker = new Worker(new URL('./nice.worker.js', import.meta.url));

    myWorker.onmessage = function (oEvent) {
      console.log('Worker said : ' + oEvent.data);
    }

    myWorker.postMessage('ali'); */
  }

   logDeviceInfo = async () => {
    const info = await Device.getInfo();
  
    console.log('Device info',info);
  };

  get pathname(){
    return  window.location.pathname
  }

  get color() {
    return '#797979'
  }

  updateList() {

    /*  this.notificationsService.registerCallback(
       'despachos',
       () => {
         this.despachoRule.getList({ updateStore: true })
       }
     ) */

    document.addEventListener('pause', function () {
      // console.log('App going to background');
    });

    document.addEventListener('resume', function () {
      // console.log('App coming to foreground');
    });

  }
  
  async synchWhenOnline() {
    try {
      await this.storage.get('eventEdit').then((req) => {
        JSON.parse(req).forEach(element => {
          this.eventservice.editEvent(element, 2, 3).subscribe((res) => {
            this.storage.remove('eventEdit')
            //this.sqliteservice.deleteeventsTable();
            console.log('eventEdit synchnize', res)
          })
        });
      })
    } catch (error) {
      console.log('error synch eventedit')
    }

    try {
      await this.storage.get('eventDelete').then((req) => {
        JSON.parse(req).forEach(element => {
          console.log('DELETE data SYNC', element)
          this.eventservice.deleteEvent(element.eventid, element.eventDeleteType, element.calendarName).subscribe((res) => {
            this.storage.remove('eventDelete')
            console.log('eventDelete synchnize', res)
          })
        });
      })
    } catch (error) {
      console.log('error delete event synch')
    }

    try {
      await this.storage.get('event-listRever').then((req) => {
        JSON.parse(req).forEach(element => {
          console.log('REVER data SYNC', element)
          this.processservice.PostTaskAction(element).subscribe((res) => {
            this.storage.remove('event-listRever')
            console.log('event-listRever synchnize', res)
          })
        });
      })
    } catch (error) {
      console.log('error event-list rever synch')
    }

    this.sqliteservice.deleteAllTables();
  }

}

