import { Component, ViewChild } from '@angular/core';
import { Nav, Platform, AlertController, Events,Toggle } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { Network } from '@ionic-native/network';
import { OneSignal } from '@ionic-native/onesignal';
import { LocationAccuracy } from '@ionic-native/location-accuracy';
import { Storage } from "@ionic/storage";
import { Myservice } from "../providers/myservice";
import { driver } from "../models/mymodel";
import * as firebase from 'firebase';
import { LocalNotifications } from '@ionic-native/local-notifications';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;
  @ViewChild('toggle') ionToggle: Toggle;

  rootPage: string;

  pages: Array<{ title: string, component: any }>;
  local: driver
  status: boolean
  pushId: string

  constructor(public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen, private network: Network, private alertCtrl: AlertController, private oneSignal: OneSignal, private locationAccuracy: LocationAccuracy, private storage: Storage, private myservice: Myservice, public events: Events, private localNotifications: LocalNotifications) {
    // , private localNotifications: LocalNotifications
    this.initializeApp();

  }

  initializeApp() {
    this.platform.ready().then(() => {
      // this.initOnesignal();
      this.statusBar.styleDefault();
      this.splashScreen.hide();

      let disconnectSubscription = this.network.onDisconnect().subscribe(() => {
        const alert = this.alertCtrl.create({
          title: 'Network Error',
          message: 'No Internet Connection',
          buttons: [
            {
              text: 'Quit',
              handler: data => {
                this.platform.exitApp();
              }
            }, {
              text: 'Cancel',
              role: 'cancel'
            }
          ]
        });
        alert.present();
      });

      // this.enableLoc()

      this.events.subscribe('driver:profile', data => {
        this.local = data
        if (this.local) {
          this.local.image = this.local.image.startsWith("http") ? this.local.image : this.myservice.base_url + this.local.image;
          this.checkStatus()
        }
      })

      this.storage.get('driver_data').then(data => {
        if (data != null) {
          this.local = data
          this.rootPage = 'HomePage'
          this.checkStatus()
        }
        else {
          this.rootPage = 'LandingPage'
        }
      })
    });
  }

  statusChange() {
      if (this.status == true)
        var stat = 'online'
      else
        var stat = 'offline'
      firebase.database().ref("drivers/" + this.pushId + "/").update({ status: stat })
  }

  checkStatus() {
    // this.oneSignal.getIds().then((id) => {
    // this.myservice.load_post({deviceid:id.userId,driverid:this.local.id},'updateDeviceid')
    // })
    var This = this
    var query = firebase.database().ref("drivers/").orderByChild("id").equalTo((this.local.id))
    query.once("child_added", function (snapshot) {
      This.pushId = snapshot.val().push_id
      console.log(snapshot.val().status)
      if (snapshot.val().status == 'online')
        This.status = true
      else
        This.status = false
    });

    var intr = setInterval(()=>{
      This.myservice.load_post({ id: This.local.id }, 'getMyStatus').subscribe(resp => {
        if (resp.status == 'success') {
          if (resp.data.user_status == "Active"){
            console.log('act')
            This.ionToggle.disabled = false;
            clearInterval(intr);
          }
          else{
            console.log('inact')
            This.ionToggle.disabled = true;
          }
        }
      })
    },20000)
  }

  openPage(page) {
    if (page == 'LandingPage') {
      this.storage.clear()
    }
    this.nav.setRoot(page);
  }

  initOnesignal() {
    this.oneSignal.startInit('ec007986-ae84-45fb-a770-f5be1e203acd', '151146703576');

    this.oneSignal.inFocusDisplaying(this.oneSignal.OSInFocusDisplayOption.InAppAlert);

    this.oneSignal.handleNotificationReceived().subscribe(() => {
      // do something when notification is received
    });

    this.oneSignal.handleNotificationOpened().subscribe(() => {
      // do something when a notification is opened
      // this.nav.setRoot('QuickridePage')
    });

    this.oneSignal.endInit();
  }

  enableLoc() {
    this.locationAccuracy.canRequest().then((canRequest: boolean) => {

      if (canRequest) {
        // the accuracy option will be ignored by iOS
        this.locationAccuracy.request(this.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY).then(
          () => console.log('Request successful'),
          error => console.log('Error requesting location permissions', error)
        );
      }

    });
  }

  setlocalNotification(){
    this.localNotifications.schedule({
      text: 'Delayed ILocalNotification',
      title: 'CMC-Driver',
      trigger: { at: new Date(new Date().getTime() + 120000) },
      led: 'FF0000',
      sound: null
    });
  }

}
