import { Component, ViewChild } from '@angular/core';
import { Nav, Platform, Events } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

/*-------------------Edited By Adarsh--------------------------*/

import { Storage } from '@ionic/storage';
import { Network } from '@ionic-native/network';
import { Common } from "../providers/services/common";
import { Myservice } from "../providers/services/myservice";
import { user } from "../models/mymodel";
import { TranslateService } from '@ngx-translate/core';
import { OneSignal } from '@ionic-native/onesignal';

/*-------------------Edited by Adarsh End ----------------------*/

@Component({
  templateUrl: 'app.html'
})
export class TruebusMyApp {
  @ViewChild(Nav) nav: Nav;
  rootPage: any = 'HomePage';
  result:any;
  local:user;
  lang: string = 'en';
  device_id:any
  lan:any;
  constructor(
    public platform: Platform,
    public statusBar: StatusBar,
    public splashScreen: SplashScreen,
    public network: Network,
    public common: Common,
    public myservice: Myservice,
    public storage: Storage,
    public events: Events,
    private translate: TranslateService,
    public oneSignal: OneSignal
    ) {
      console.log('truebuss');
      this.initializeApp();  
      this.translate.setDefaultLang('ar');
      this.translate.use('ar');  
      this.translate.setDefaultLang('en');
      this.translate.use('en'); 
      events.subscribe('user:created', (user, time) => {
        this.local = user;
      }); 
    }
    
    updateItem(item){
      console.log(item);
      this.lang = item==true?'ar':'en';
      this.storage.set('lang', this.lang);
      this.events.publish('user:lang', this.lang);
      this.languageTrans();
    }
    
    initializeApp() {
      this.platform.ready().then(() => {      
        this.statusBar.styleDefault();
        this.splashScreen.hide();
        var This = this;
        setTimeout(function(argument) {
          This.languageTrans();
        },500)     
        //
        this.events.subscribe('app:lang', data => {
          console.log("called");
          this.languageTrans();
        })
        //this.triggerNotification();
        this.network.onDisconnect().subscribe(() => {     
          this.common.presentToast('network was disconnected');
        });
        
        this.network.onConnect().subscribe(() => {
          this.common.presentToast('network connected');
          setTimeout(() => {
            if (this.network.type === 'wifi') {
              console.log('we got a wifi connection, woohoo!');
            }
          }, 3000);
        });
        var data = {"app_key":"my_key"};
        this.myservice.post_data('get_app_details',data).then(res=> {
          this.result = res;
          if(this.result.status!=='success'){
            this.nav.setRoot("ErrorPage");
          }
          console.log(res);
        }).catch(res=>{
          console.log(res);
        })
        this.storage.get('user_data').then(data => {
          console.log(data)
          if (data) {
            this.local = data
          }
        })
      });
    }
    
    triggerNotification()
    {
      // Define settings for iOS
      var iosSettings = {};
      iosSettings["kOSSettingsKeyAutoPrompt"] = false;
      iosSettings["kOSSettingsKeyInAppLaunchURL"] = false; 
      // Initialise plugin with OneSignal service
      this.oneSignal.startInit('0594aad6-6487-4140-8fc0-1822ea653100', '893149145204').iOSSettings(iosSettings);
      this.oneSignal.registerForPushNotifications();
      // Control how OneSignal notifications will be shown when 
      // one is received while your app is in focus
      this.oneSignal.inFocusDisplaying(this.oneSignal.OSInFocusDisplayOption.None);
      // Retrieve the OneSignal user id and the device token
      this.oneSignal.getIds().then((ids) => {
        console.log('getIds: ' + JSON.stringify(ids));
        this.device_id =ids;
        console.log(this.device_id)
        this.storage.set('get_deviceId',this.device_id);
        // this.myservice.load_post({ device_id:ids },"store_id").subscribe(response => { })
      });
      // When a push notification is received handle 
      // how the application will respond
      this.oneSignal.handleNotificationReceived().subscribe((msg) => {
        // Log data received from the push notification service
        console.log('Notification received');
        console.dir(msg);
      }); 
      // When a push notification is opened by the user
      // handle how the application will respond
      this.oneSignal.handleNotificationOpened().subscribe((msg) => {
        // Log data received from the push notification service
        console.log('Notification opened');
        /*console.log(JSON.stringify(msg));
        var pool_id = msg.notification.payload.additionalData.pool_id;
        if(pool_id)
        this.nav.setRoot('QuoteDetailsPage',{'pool_id' : pool_id,'from_push' : false});*/
        //console.log(this.event_id);
        //this.detail(this.event_id);
      });
      // End plugin initialisation
      this.oneSignal.endInit();
    }
    
    cancelticket() {
      this.nav.setRoot("CanceltripPage");
    }
    
    home() {
      this.nav.setRoot("HomePage");
    }
    
    login() {
      console.log("asdsadasdsa");
      this.storage.remove('user_data');
      this.local = undefined;
      this.nav.setRoot("LoginPage");
    }
    
    changepass() {
      this.nav.setRoot("ChangepassPage");
    }
    
    trip_list(){
      console.log("trip_list");
      this.nav.setRoot("TripPage");
    }
    
    notification(){
      this.nav.setRoot("NotificationPage");
    }
    
    signup(){
      this.nav.setRoot("SignupPage");
    }
    
    forgot(){
      this.nav.setRoot("ChangepassPage");
    }
    
    signin(){
      this.nav.setRoot("LoginPage");
    }
    
    languageTrans() {
      var This = this;
      setTimeout(function () {
        This.storage.get('lang').then(data => {
          console.log(data)
          if (data) {
            This.translate.setDefaultLang(data);
            This.translate.use(data);
            This.lang = data;
            if(data=='ar'){
              This.lan = true;
            }
          }
          else {
            This.translate.setDefaultLang('en');
            This.translate.use('en');
          }
          //This.lang_trans()
        })
      }, 500)
    }
  }