import { Component, ViewChild  } from '@angular/core';
import { Nav, Platform ,Events,ToastController,IonicApp,AlertController} from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { Storage } from '@ionic/storage';
import { PermissionsService } from '../providers/permissionservice';
import { Geolocation } from '@ionic-native/geolocation';
import { OneSignal } from '@ionic-native/onesignal';
import { Network } from '@ionic-native/network';
import {Myservice} from '../providers/myservice';
import { Badge } from '@ionic-native/badge';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;
	rootPage:any = 'LandingPage';
	user_data:any;
	device_id:any;
	 toast:any;
	 notify:any;
	 
  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen,public events:Events,public storage:Storage, private permission: PermissionsService,private geolocation: Geolocation,private oneSignal: OneSignal,private network: Network, private toastCtrl: ToastController, private myservice: Myservice, private ionicApp: IonicApp, private alertCtrl: AlertController,private badge: Badge) {
   
   

this.events.publish('user:notifications', '');

   platform.ready().then(() => {
	   
	   
	        console.log("out app notificatn outside");
   this.badge.isSupported().then((data) => {
	   console.log(data,"in app notificatn Supported");
	   });
	   this.badge.requestPermission().then((data) => {
	   console.log(data, "in app notificatn Permission");
	   if(data){
		    this.badge.set(10);
	   }
	   	else {
					console.log('Not Granted loc');
				}
	   });	  
	   this.badge.hasPermission().then((data) => {
	   console.log(data, "in app notificatn hasPermission");
	   if(data){
		    this.badge.set(10);
	   }
	   	else {
					console.log('Not Granted hasPermission');
				}
	   });
	   this.badge.get().then((data) => {
	   console.log(data,"get badge noti");
	   });
	   this.badge.set(10);
	   
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
	  
	  //network starts
	  
	 /* platform.registerBackButtonAction(() => {
            // get current active page
            let view = this.nav.getActive();
            //if (view.component.name == "SuccessPage") {
               /* //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();
                } slash *
           // } else {
                // go to previous page
              //  this.nav.pop({});
           // }
		   console.log(view.id)
		   console.log("view page", view.component.name)
		   if(view.id=='TabsPage') {
				platform.exitApp();
		   }
		    if(view.id=='SuccessPage') {
				this.nav.setRoot('TabsPage');
		   }
		    if (this.nav.canGoBack()) { // CHECK IF THE USER IS IN THE ROOT PAGE.
			console.log("in back")
      this.nav.pop(); // IF IT'S NOT THE ROOT, POP A PAGE.
    } else {
		console.log("exit back")
      platform.exitApp(); // IF IT'S THE ROOT, EXIT THE APP.
    }
        });
		
		  var ready = true;
           platform.registerBackButtonAction(function () {
                console.log("registerback");
                console.log(this.ionicApp);
                var activePortal = this.ionicApp._loadingPortal.getActive() ||
                    this.ionicApp._toastPortal.getActive() ||
                    this.ionicApp._overlayPortal.getActive();
                if (activePortal) {
                    ready = false;
                    activePortal.dismiss();
                    activePortal.onDidDismiss(function () { ready = true; });
                    return;
                }
                if (this.nav.length() == 1) {
                    this.confirmExitApp();
                }
                else {
                    this.nav.pop();
                }
		
		  platform.registerBackButtonAction(() => {
        let nav = this.nav.getActive();
	 
        if (this.nav.canGoBack()){ //Can we go back?
          this.nav.pop();
        }else{
          platform.exitApp(); //Exit from app
        }
      });*/
     
	
	
            
  
	  
	  if (this.network.type === 'none') {
				console.log('network was disconnected :-(');
				this.presentToast('No network connection');
			}
	
			let disconnectSubscription = this.network.onDisconnect().subscribe(() => {
				console.log('network was disconnected :-(');
				console.log("hi");
				this.presentToast('network was disconnected');
			});

			// stop disconnect watch
			//disconnectSubscription.unsubscribe();


			// watch network for a connection
			let connectSubscription = this.network.onConnect().subscribe(() => {
				console.log('network connected!');
				this.closeToast();
				// We just got a connection but we need to wait briefly
				// before we determine the connection type. Might need to wait.
				// prior to doing any api requests as well.
				setTimeout(() => {
					if (this.network.type === 'wifi') {
						console.log('we got a wifi connection, woohoo!');
						//this.presentToast('we got a wifi connection');
	 
					}
				}, 3000);

				
			});
	  
	  
	  
	  //network ends
	  
	  
     // statusBar.styleDefault();
      statusBar.hide();
	  statusBar.overlaysWebView(true);
      splashScreen.hide();
	  this.geolocation.getCurrentPosition().then(pos => {
				this.storage.set('lat_lng', {'lat': pos.coords.latitude ,'lng':pos.coords.longitude});
			});
				
		this.triggerNotification();
		
		
    });
	this.storage.get('user_data').then((user_data) => {
			if(user_data){
				this.user_data=user_data;
				// this.myservice.get_notifications(this.user_data.id);
				
			}
		})
	
	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:notifications', userdetails => {	
	//	this.get_notifications(userdetails);
	//});
		
				this.permission.checkLocationPermissions().then(permissionOk => {
			if (permissionOk) {
				this.permission.checkCameraPermissions().then(permissionOk => {
				if (permissionOk) {
					console.log('Granted cam');

					this.permission.checkMicPermissions().then(permissionOk => {
						if (permissionOk) {
							console.log('Granted mic');
						}
						else {
							console.log('Not Granted mic');
						}
					})
				}
				else {
					console.log('Not Granted cam');
				}
			})
			}
				else {
					console.log('Not Granted loc');
				}
				})
		
  }
  
  confirmExitApp(){
        
        var alert = this.alertCtrl.create({
            title: "CONFIRMATION",
            message: "Quit App ?",
            buttons: [
                {
                    text: 'Cancel',
                    handler: function () {
                    }
                },
                {
                    text: 'Ok',
                    handler: function () {
                        this.platform.exitApp();
                    }
                }
            ]
        });
        alert.present();
    }
  logout() {
   this.storage.remove('user_data');
   this.events.publish('user:update_profile', '');
   this.nav.setRoot('LoginPage');
}
login(){
	this.nav.setRoot('LoginPage');
}
 
home(){
	this.nav.setRoot('TabsPage');
}
offers(){
	this.nav.setRoot('Moreoffers');
}
request_quotes(){
	this.nav.setRoot('RequestQuote');
}
legal_notice(){
	this.nav.setRoot('LegalnoticePage');
}
edit_profile(){
		this.nav.setRoot('AddcarPage');
	
}
view_booking(){
		this.nav.setRoot('Booking');
	
}

	 /*push notification starts*/

	triggerNotification()
	{

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


      // Initialise plugin with OneSignal service
       this.oneSignal.startInit('2b04ea88-bd29-47be-85ec-53012c3d4f74', '935901141024').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();

   }

/*push notification ends*/

	presentToast(msg) {
		this.toast = this.toastCtrl.create({
			message: msg,
			position: 'bottom'
		});
		this.toast.present();

		this.toast.onDidDismiss(() => {
			//this.closeToast();
			console.log('Dismissed toast');
		});
		
	}
  
    closeToast() {
		if(this.toast) {
			console.log("hi,close the toast");
			this.toast.dismiss();
		}
	}
	
	


}
