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';
import { TranslateService } from '@ngx-translate/core';

@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;
  lang: string = 'en';
  title: string
  msg: string
  quit: string
  cancel: 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 data: dataService, private geolocation: Geolocation, private translate: TranslateService) {
    this.initializeApp();

  }

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

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

      this.languageTrans();
      this.events.subscribe('driver:lang', data => {
        this.languageTrans();
      })

      this.network.onDisconnect().subscribe(() => {
        const alert = this.alertCtrl.create({
          title: this.title,
          message: this.msg,
          buttons: [
            {
              text: this.quit,
              handler: data => {
                this.platform.exitApp();
              }
            }, {
              text: this.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.Notification);

    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++) {
         var t = new Date(upcoming[i].pickup_date + ' ' + upcoming[i].pickup_time).getTime()
          // console.log(t-300000)
          arr.push({
            id: i,
            text: 'Ride Notification',
            title: 'CMC-Driver',
            trigger: { at: new Date(t - 300000) },
            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})
      })
  }

  languageTrans() {
    var This = this;
    setTimeout(function () {
      This.storage.get('lang').then(data => {
        console.log(data)
        if (data) {
          This.translate.use(data);
          This.lang = data;
        }
        else {
          This.translate.setDefaultLang('en');
        }
        This.lang_trans()
      })
    }, 500)
  }

  lang_trans() {
    this.translate.get(['sidemenu.Network Error', 'sidemenu.No Internet Connection', 'sidemenu.Quit', 'sidemenu.Cancel']).subscribe(value => {
      this.title = value["sidemenu.Network Error"]
      this.msg = value["sidemenu.No Internet Connection"]
      this.quit = value["sidemenu.Quit"]
      this.cancel = value["sidemenu.Cancel"]
    })
  }

  changeLang(lang) {
    this.storage.set('lang', lang);
    this.events.publish('driver:lang', lang);
  }

}
