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';
import { dataService } from "../providers/common.service";
import { Geolocation } from '@ionic-native/geolocation';

@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
  locSubs: any;

  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 data: dataService, private geolocation: Geolocation) {
    this.initializeApp();

  }

  initializeApp() {
    this.platform.ready().then(() => {

      // this.statusBar.styleLightContent();
      // this.initOnesignal();
      // this.enableLoc()

      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.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.events.subscribe('driver:locOff',_=>{
        this.locSubs.unsubscribe();
      })

      // this.events.subscribe('driver:locOn',_=>{
      //   this.liveLoc();
      // })

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

  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) => {
    //   console.log(id.userId)
    // this.myservice.load_post({deviceid:id.userId,driverid:this.local.id},'updateDeviceid').subscribe(resp=>{
    //   console.log(resp)
    // })
    // })
    console.log(this.local)
    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)
    // This.setlocalNotification();
  }

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

    this.oneSignal.handleNotificationOpened().subscribe((data) => {
      // do something when a notification is opened
      var additionalData = data.notification.payload.additionalData
      this.storage.get('driver_data').then((user_data) => {
        if(user_data)
          this.nav.push('QuickridePage', { id: additionalData.bookingId, from: additionalData.from})
        else
          this.nav.setRoot('SigninPage', { id: additionalData.bookingId, from: additionalData.from })
      })
    });

    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.myservice.load_post({ id: this.local.id }, 'getMyRides').subscribe(response => {
      
      if (response.status == 'success') {
        var upcoming = response.data.upcoming

        var arr = []
        for (let i = 0; i < upcoming.length; i++) {
          arr.push({
            id: i,
            text: 'Ride Notification',
            title: 'CMC-Driver',
            trigger: { at: new Date(upcoming[i].pickup_date + ' ' +upcoming[i].pickup_time) },
            led: 'FF0000',
            sound: 'file://assets/sounds/request.mp3',
            data: upcoming[i],
            vibrate:true,
          })

          if(i == upcoming.length-1){
            this.localNotifications.schedule(arr);
          }
        }
      }
    })

    this.localNotifications.on('click').subscribe(rideData=>{
      this.data.setrideData(rideData.data)
      this.nav.push('RidedetailsPage')
    })
  }

  liveLoc(){
    this.locSubs = this.geolocation.watchPosition().filter((p) => p.coords !== undefined) //Filter Out Errors
      .subscribe(position => {
        firebase.database().ref("drivers/" + this.pushId + "/").update({ lat: Number(position.coords.latitude), lng: Number(position.coords.longitude) })
        // firebase.database().ref("drivers/" + this.pushId + "/").update({
        //   lat: 10.014638, lng: 76.364054})
      })
  }

}
