/* eslint-disable */
/* tslint:disable */
///<reference path="../../../plugins/cordova-plugin-mfp/typings/worklight.d.ts" />
///<reference path="../../../plugins/cordova-plugin-mfp-push/typings/mfppush.d.ts" />
import { Component, OnInit, NgZone } from '@angular/core';
import { Event } from '../models/event.model';
import { NotificationsService } from '../services/notifications.service';
import { WebNotificationsService } from '../services/webnotifications.service';
import { ModalController, AlertController, AnimationController, Platform } from '@ionic/angular';
import { Router, ActivatedRoute } from '@angular/router';
import { ToDayEventStorage } from '../store/to-day-event-storage.service';
import { DocumentCounterService } from 'src/app/OtherService/document-counter.service'
import { PermissionService } from '../OtherService/permission.service';
import { TotalDocumentStore } from '../store/total-document.service';
import { connection } from '../services/socket/synchro.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 * as Sentry from "@sentry/browser";
// import { Integrations } from "@sentry/tracing";

// Sentry.init({
//   dsn: "https://b374f7c7e09a49adb04197845ded60e9@o927946.ingest.sentry.io/5877459",
//   integrations: [new Integrations.BrowserTracing()],

//   // Set tracesSampleRate to 1.0 to capture 100%
//   // of transactions for performance monitoring.
//   // We recommend adjusting this value in production
//   tracesSampleRate: 1.0,
// });

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

  connection = connection

  constructor(
    private zone: NgZone,
    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) {

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

    this.updateList()


    window['inactivity/function'] = () => {
      if(window.location.pathname != '/inactivity') {

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


    // if (typeof Worker !== 'undefined') {
    //   // Create a new
    //   const worker = new Worker(new URL('./nice.worker.ts', import.meta.url));
    //   worker.onmessage = ({ data }) => {
    //     console.log(`page got message: ${data}`);
    //   };
    //   worker.postMessage('hello');
    // } else {
    //   // Web workers are not supported in this environment.
    //   // You should add a fallback so that your program still executes correctly.
    // }

  }
  

  refreshing() {
    
  }

  ngOnInit() {
    /* this.network.checkNetworkConnection;
    this.network.checkNetworkDisconnection; */
    console.log('Active route ', this.router.url)
    if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
      this.webnotification.webconnection();
      this.webnotification.onReceviNotificationWeb();
    } else {
      this.mobilefirstConnect();
      this.notificationsService.getAndpostToken2();
      this.notificationsService.onReceviNotification();
    }

  }

  

  mobilefirstConnect() {

    if(window['WLAuthorizationManager']) {
      if(window['WLAuthorizationManager'].obtainAccessToken) {
        window['WLAuthorizationManager'].obtainAccessToken("").then((token) => {
  
          console.log('MobileFirst Server connect: Success ' + token);
    
          var resourceRequest = new WLResourceRequest("/adapters/javaAdapter/resource/greet/",
            WLResourceRequest.GET
          );
    
          resourceRequest.setQueryParameter("name", "world");
          resourceRequest.send().then(
            (response) => {
              // Will display "Hello world" in an alert dialog.
              console.log("Connect with JavaAdapter Success: " + response.responseText);
              //this.MFPushNotification();
            },
            (error) => {
              console.log("Connect with JavaAdapter Failure: " + JSON.stringify(error));
            }
          );
        }, (error) => {
          console.log('MobileFirst Server connect: failure ' + error.responseText);
          console.log(JSON.stringify(error))
          /* this.zone.run(() => {
            console.log("Bummer...");
            console.log("Failed to connect to MobileFirst Server");
          }); */
        });
      }
    }
  }

  updateList() {

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

  }

}
