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';
import { Storage } from '@ionic/storage';
import { OneSignal } from '@ionic-native/onesignal';
import {Myservice} from '../providers/myservice';
import { Geolocation } from '@ionic-native/geolocation';
import { LocationAccuracy } from '@ionic-native/location-accuracy';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;
	rootPage:any = 'LandingPage';
	user_data:any;
	open_count:any;
	device_id:any;
	noti_count:any = 0;
	
	constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen,public events:Events,public storage:Storage,private oneSignal: OneSignal, private myservice: Myservice,private geolocation: Geolocation,private locationAccuracy: LocationAccuracy) {
	 
		events.subscribe('user:notifications', userdetails => {	
			 this.get_noti_count();
		});
		this.storage.get('user_data').then((user_data) => {
			if(user_data){
				this.user_data=user_data;
				 this.get_booking();
				 this.get_noti_count();
			}
		})
		setInterval(() => {
			this.storage.get('user_data').then((user_data) => {
			if(user_data){
				this.user_data=user_data;
				 this.get_booking();
				 this.get_noti_count();
			}
		})
				
		}, 5000);
		platform.ready().then(() => {
			// Okay, so the platform is ready and our plugins are available.
			// Here you can do any higher level native things you might need.
			//statusBar.styleDefault();
			statusBar.hide();
			statusBar.overlaysWebView(true);
			splashScreen.hide();
			
			this.enable_location();
			this.geolocation.getCurrentPosition().then(pos => {
				console.log('lat: ' + pos.coords.latitude + ', lon: ' + pos.coords.longitude);
				console.log(pos);
				this.storage.set('lat_lng', {'lat': pos.coords.latitude ,'lng':pos.coords.longitude});
			});			
			this.triggerNotification();
			platform.registerBackButtonAction(() => {
            // get current active page
            let view = this.nav.getActive();
            if (view.component.name == "ListVehiclePage") {
               /* //Double check to exit app
                if (new Date().getTime() - lastTimeBackPress < timePeriodToExit) {
                    this.platform.exitApp(); //Exit from app
                } else {
                    let toast = this.toastCtrl.create({
                        message:  'Press back again to exit App?',
                        duration: 3000,
                        position: 'bottom'
                    });
                    toast.present();
                    lastTimeBackPress = new Date().getTime();
                } */
            } else {
                // go to previous page
                this.nav.pop({});
            }
        });
		});
			this.storage.get('user_data').then((user_data) => {
			if(user_data){
				this.user_data=user_data;
				 this.get_booking();
			}
		})
		events.subscribe('user:update_profile', userdetails => {	
			console.log("app comp", userdetails);
			if(userdetails !== undefined && userdetails !== ""){
				this.storage.set('user_data', userdetails);
				this.user_data = userdetails;
				console.log("profile", this.user_data);
			}
			else {
				console.log("logout");
				this.storage.remove('user_data');
				this.user_data =  '';
			}
		});
		events.subscribe('user:incomp_read_status', userdetails => {	
			 this.get_booking();
		});
		
		
	}
	
	logout() {
		this.storage.remove('user_data');
		this.events.publish('user:update_profile', '');
		this.nav.setRoot('LoginPage');
	}
	edit_pro(){
		this.nav.setRoot('AddcarPage');
	}
login(){
	this.nav.setRoot('LoginPage');
}
booking(){
	this.nav.setRoot('Booking');
}
home(){
	this.nav.setRoot('ListVehiclePage');
}
schedule(){
	this.nav.setRoot('TimingPage');
}
addoffers(){
	this.nav.setRoot('Addoffers');
}
viewoffers(){
	this.nav.setRoot('Viewoffers');
}
viewservices(){
	this.nav.setRoot('Selected_services');
}



/*location accuracy starts */

	
	enable_location() {
		let options = {
			enableHighAccuracy: true
		};
		this.locationAccuracy.canRequest().then((res: boolean) => {
			if (res) {
				//console.log(this.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY);
				let location_accuracyy = Number(this.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY);
				let location_accuracy = location_accuracyy.toString();
				this.locationAccuracy.request(location_accuracyy).then((loc) => {
					this.geolocation.getCurrentPosition().then(pos => {
						console.log('lat: ' + pos.coords.latitude + ', lon: ' + pos.coords.longitude);
						console.log(pos);
						this.storage.set('latitude', pos.coords.latitude);
						this.storage.set('longitude', pos.coords.longitude);
		
					}).catch((err) => {
						// alert(err);
					})
				}, (error) => {
						//  alert(error); 
					})
			}
		})
	}


/*location accuracy ends */


 /*push notification starts*/

	triggerNotification()
	{

      // Define settings for iOS
      var iosSettings = {};
      iosSettings["kOSSettingsKeyAutoPrompt"] = false;
      iosSettings["kOSSettingsKeyInAppLaunchURL"] = false; 


      // Initialise plugin with OneSignal service
       this.oneSignal.startInit('46d0af64-c191-4ec6-9f29-d8b6232dae8a', '912269327554').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));
		 if(msg.notification.payload.additionalData.pool_id.type == 'request'){
			var pool_id = msg.notification.payload.additionalData.pool_id.pool_id;
			 console.log("pool_id", pool_id);
			if(pool_id)
				this.nav.setRoot('VehicleDetailPage',{'pool_id': pool_id,'from_push' : false});
		 }else{
			 var book_id = msg.notification.payload.additionalData.pool_id.id;
			 var stat = msg.notification.payload.additionalData.pool_id.stat;
			if(book_id)
				this.nav.setRoot('BookingDetail',{'id' :book_id,'stat' :stat ,'from_push' : false});
				 
		 }
		 //console.log(this.event_id);
		 //this.detail(this.event_id);
      });


      // End plugin initialisation
     this.oneSignal.endInit();

   }
   
    get_booking(){
  
  	//this.myservice.show_loader();
		this.myservice.load_get('getBookingsopen/id/'+this.user_data.id).subscribe(data => {
			//this.myservice.hide_loader();
			if(data.status == 'success'){
				this.open_count = data.data.open_book;
				console.log("comp book",data);
				 
			}
		});
  }

      get_noti_count(){
  
  //	this.myservice.show_loader();
		this.myservice.load_get('getnoticount/id/'+this.user_data.id).subscribe(data => {
			//this.myservice.hide_loader();
			if(data.status == 'success'){
				this.noti_count = data.data;
				console.log("noti_count",data);
				 
			}
			else{
				this.noti_count = 0;
			}
		});
  }
  legal_notice(){
	this.nav.setRoot('LegalnoticePage');
}
/*push notification ends*/

}