import { SplitpaneProvider } from './../providers/splitpane/splitpane';
import { Component, ViewChild } from '@angular/core';
import { App, IonicApp, Nav, Platform, Config, AlertController, LoadingController, MenuController } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { TranslateService } from '@ngx-translate/core';
import { Storage } from '@ionic/storage';
import { Insomnia } from '@ionic-native/insomnia';

import { Profile } from '../pages/profile/profile';
import { LoginPage } from '../pages/login/login';
import { HomePage } from '../pages/home/home';
import { OnboardingPage } from '../pages/onboarding/onboarding';
import { FarmaciaPage } from '../pages/farmacia/farmacia';
import { AyudaPage } from '../pages/ayuda/ayuda';


//import { MimaskotUser } from '../models/mimaskot-user.model';
import {UserService} from "../services/user.service";
import { AuthService } from '../services/auth.service';
import { Pata } from '../pata';
import { FCM } from '@ionic-native/fcm';

import { environment } from "../environments/environment"
import { Market } from '@ionic-native/market';
import { HistorialPage } from '../pages/historial/historial';
import { PagosPage } from '../pages/pagos/pagos';
import { PedidosPage } from '../pages/pedidos/pedidos';
import { RecetaPage } from '../pages/receta/receta';
import { ModalCart } from '../modals/cart/cart';
import { ModalDetallesPage } from '../modals/modal-detalles/modal-detalles';
import { ModalCheckout } from '../modals/checkout/checkout';
import { TrackingProvider } from '../providers/tracking/tracking';
import { InAppBrowser } from '@ionic-native/in-app-browser';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;
  rootPage: any = null;
  public staticUrl:string;
  appInvite: boolean = true;
  public storeName: string = "";

  pages: Array<{title: string, component: any, selected: boolean, inviteOff: boolean}>;

  user: any;
  /*active: any;*/
  zones: any = [];
  loading: any; 
  iam: any = {lat:0,lng:0};
  success: boolean = false;

  constructor(
    public platform: Platform,
    public statusBar: StatusBar,
    public splashScreen: SplashScreen,
    private translate: TranslateService,
    private config: Config,
    private storage: Storage,
    private app: App,
    private ionicApp: IonicApp,
    private service: Pata,
    private alertCtrl: AlertController,
    private userService:UserService,
    private loadingController: LoadingController,
    private authService:AuthService,
    private fcm: FCM,
    public split: SplitpaneProvider,
    public locationTracker: TrackingProvider,
    public menu: MenuController,
    private insomnia: Insomnia,
    public iab: InAppBrowser,
    private market: Market
  ){

    this.initializeApp();

  }
  
  initializeApp() {
    this.platform.ready().then(() => {
      console.log("plataforma ready")
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      
      this.staticUrl = environment.staticUrl;
      
      this.appInvite = this.service.appInvite;
      
      this.iam.lat = this.locationTracker.UbicacionLat();
      this.iam.lng = this.locationTracker.UbicacionLng();
  
      this.authService.version(environment.version).subscribe((data:any) => {
        if (data.res == "ERR") {
          let alert = this.alertCtrl.create({
            title: 'Actualiza MY',
            message: data.msg,
            buttons: [
              {
                text: 'Ir a actualizar',
                handler: () => {
                  if (this.platform.is('ios')) {
                    this.market.open('1451771784');
                    this.platform.exitApp();
                  }
                  else if (this.platform.is('android')) {
                    //this.market.open('cl.myoda.app');
                    this.iab.create("https://www.yodalife.cl", "_system");
                  }
                  return false;               
                }
              }
            ],
            enableBackdropDismiss: false
          });
          alert.present();
        }
      });
  
      this.userService.changeAvatar.subscribe((st) => {
        console.log(st);
        this.user.avatar = st;
      });

      Date.prototype.toISOString = function() {
        var tzo = -this.getTimezoneOffset(),
            dif = tzo >= 0 ? '+' : '-',
            pad = function(num) {
                var norm = Math.floor(Math.abs(num));
                return (norm < 10 ? '0' : '') + norm;
            };
        return this.getFullYear() +
            '-' + pad(this.getMonth() + 1) +
            '-' + pad(this.getDate()) +
            'T' + pad(this.getHours()) +
            ':' + pad(this.getMinutes()) +
            ':' + pad(this.getSeconds()) +
            dif + pad(tzo / 60) +
            ':' + pad(tzo % 60);
      }
      
      setTimeout(() => {
        this.splashScreen.hide();
      },0);

      setTimeout(()=>{
        if (this.success == false) {
          this.welcomeApp();  
        }
      },4000);

      this.service.startApp.subscribe((start:any) => {
        this.appInvite = this.service.appInvite;
        this.success = true;
        console.log('this.appInvite: '+this.appInvite);
        this.welcomeApp();
      });

      this.service.launch();

      if (this.platform.is('ios')){
        this.statusBar.overlaysWebView(true);
        this.statusBar.styleBlackOpaque();
        this.statusBar.styleLightContent();
      }
      else if (this.platform.is('android')){
        this.statusBar.hide();
      }


      if (this.platform.is('cordova')) {
        this.platform.registerBackButtonAction(() => {
            let nav = this.app.getActiveNav();
            let view = nav.getActive().instance.pageName;

            if (view == ModalCart || view == ModalDetallesPage || view == ModalCheckout) {
              let activeModal=this.ionicApp._modalPortal.getActive();
              activeModal.dismiss();
              return;
            }
            else {
              if(this.menu.isOpen()){
                this.menu.close()
                return;
              }
              else if(this.nav.canGoBack()){
                this.nav.pop();
                return;
              }
              else {
                this.platform.exitApp();
              }
            }
        });
        if (this.platform.is('android') || this.platform.is('ios')) {
          this.fcm.getToken().then(token=>{
            //alert('push:'+ token);
            this.userService.setPush(token);
            this.authService.setPush(token);
          });
          this.fcm.onNotification().subscribe(data=>{
            console.log('onNotification');
            console.log(data);
            //alert('Push:' + JSON.stringify(data));
            if(data.wasTapped){
              console.log("Received in background", data);
            } else {
              console.log("Received in foreground", data);
            };
          })
          this.fcm.onTokenRefresh().subscribe(token=>{
            //alert('push:'+ token);
            this.userService.setPush(token);
            this.authService.setPush(token);
          });
        }   

      }

      this.authService.loginOk.subscribe(data => {
        console.log('loginOk subscribe');
        if (data.res == "OK") {
          if (data.profile.avatar == null || data.profile.avatar == "") {
            data.profile.avatar = "assets/img/default/avatar.png";
          }
          this.user = data.profile;
          //this.active = data.profile.types[0];
          //this.storage.set("active", this.active);
          this.reloadSide(); 
          this.authService.sendPushToServer(this.user.id);
        }
      });

      /*
      Translate
      this.pages.forEach((page) => {
        this.translate.get(page.titleTranslationKey).subscribe((translation) => {
          page.title = translation;
        })
      });
      */

    });

  }
  welcomeApp() {
    console.log('welcomeApp');
    this.insomnia.allowSleepAgain().then(() => console.log('success'),() => console.log('insomnia error'));
    this.storage.get("MP-FirstTime").then((val) => {
      if (val == true) {
        this.storage.get("token").then((token) => {
          localStorage.setItem('token',token);
          if (token) { this.startUser(); }
          else { this.startLogin('err => firstitme => get token => ok => else'); }
        }, (err) => { this.startLogin('err => firstitme => get token => err'); });
      }
      else {
        if (this.appInvite) { 
          /* appInvite never first time ! */
          this.storage.get("token").then((token) => {
            if (token) { this.startUser(); }
            else { this.startLogin('MP-firsttime => else -> appinvite -> ok -> else'); }
          }, () => { this.startLogin('err MP-FirstTime => else -> appinvite -> err'); });
        } 
        else { this.rootPage = OnboardingPage; this.loadingHidden(); }
      }
    }, (err) => {
      console.log('err MP-FirstTime, get token (email mode)');
      this.storage.get("token").then((token) => {
        if (token) { this.startUser(); }
        else { this.startLogin('err MP-firsttime => OK => else'); }
      }, () => { this.startLogin('err MP-FirstTime => err'); });

    });
  }
  startLogin(str:string) {
    console.log(str);
    this.rootPage = LoginPage;
    this.loadingHidden();
  }
  startUser() {
    
    this.userService.getProfile().subscribe((result:any)=>{
      this.user = result;
      this.userService.getId(result.id).subscribe((ok:any) => {
        if (ok.res == "ERR") {
          console.log('ERR: userService: getProfile : getId : Backend ERR');
          this.rootPage = LoginPage; 
          this.loadingHidden();
        }
        else {
          this.user = ok.data;
          if (this.user.avatar == null || this.user.avatar == "") {
            this.user.avatar = "assets/img/default/avatar.png";
          }
          if (this.user.level == "1") {
            this.rootPage = FarmaciaPage;
          }
          else if (this.user.level == "5") {
            this.rootPage = HomePage;
          }
          this.reloadSide();                 
          this.userService.sendPushToServer();
          this.loadingHidden();
        }
      }, (err) => {
        this.service.logError(null, "No fue posible recuperar tu perfil. Por favor accede nuevamente.");
        console.log('ERR: userService: getProfile : getId')
        this.rootPage = LoginPage; 
        this.loadingHidden();
      });
    }, (err) => {
      console.log('ERR: userService: getProfile');
      this.rootPage = LoginPage;
      this.loadingHidden();
    });
  }
  switchActive(zone:any) {
    console.log("switch zone: ",zone);
  }
  loadingHidden() {
    setTimeout(() => {
      document.getElementById("loader-spinner").classList.add("animated-start");
      document.getElementById("logo-loader").classList.add("animated");
      document.getElementById("logo-loader").classList.add("bounceOut");
      setTimeout(() => {
        document.getElementById("custom-overlay").style.display = "none";
      }, 1200);
    },500);
  }

  profile() {
    if (this.menu.isOpen()) {
      this.menu.close();
    }
    if (this.user.id == '0') {
      let alert = this.alertCtrl.create({
        title: 'Usuario no registrado',
        message: 'Sólo los usuarios registrados pueden tener un perfil',
        buttons: [
          {
            text: 'Aceptar',
            role: 'cancel',
            handler: () => {}
          }
        ]
      });
      alert.present();
    } else {
      this.nav.setRoot(Profile);
    }
  }

  reloadSide() {
    console.log('reloadSide');
    this.storeName = this.service.storeName;
    this.pages = [];
    if (this.user.level == "1") { // Usuario
      this.pages.push({ title: this.storeName, component: FarmaciaPage, selected: true, inviteOff: false });
      this.pages.push({ title: 'Mis pedidos', component: PedidosPage, selected: false, inviteOff: false });
      this.pages.push({ title: 'Mis recetas', component: RecetaPage, selected: true, inviteOff: true });
      this.pages.push({ title: 'Tarjetas y Saldos', component: PagosPage, selected: false, inviteOff: false });
      this.pages.push({ title: 'Historial', component: HistorialPage, selected: false, inviteOff: false });
      this.pages.push({ title: 'Ayuda', component: AyudaPage, selected: false, inviteOff: false });
    }
    else if (this.user.level == "5") { // Delivery
      this.pages.push({ title: 'Repartos', component: HomePage, selected: true, inviteOff: false });
      /*
      
      this.pages.push({ title: 'Mis requerimientos', component: RequerimientosPage, selected: false });
      this.pages.push({ title: 'Mis servicios', component: ServiciosPage, selected: false });
      this.pages.push({ title: 'Mis valoraciones', component: ValorizacionPage, selected: false });
      this.pages.push({ title: 'Noticias', component: NoticiasPage, selected: false });
      this.pages.push({ title: 'Ayuda', component: AyudaPage, selected: false });
      */      
    }
    
    this.zones = [];
    /*
    if (this.user.types.length > 1) {
      for (let i=0; i < this.user.types.length ; i++) {
        if (this.user.types[i].profile_id != this.active.profile_id ) {
          this.zones.push(this.user.types[i]);
        }
      }
    }
    */

  }

  openPage(page) {
    if (this.menu.isOpen()) {
      this.menu.close();
    }
    this.nav.setRoot(page.component);
  }

  closeSession() {
  if (this.menu.isOpen()) {
    this.menu.close();
  }
  let alert = this.alertCtrl.create({
    title: 'Hasta pronto',
    message: '¿Quieres volver al login?',
    buttons: [
      {
        text: 'Cancelar',
        role: 'cancel',
        handler: () => {}
      },
      {
        text: 'Confirmar',
        handler: () => {
          this.storage.remove("token");
          this.storage.remove("MP-Profile");
          localStorage.removeItem('token');
          this.storage.remove("active");
          this.nav.setRoot(LoginPage);
        }
      }
    ]
  });
  alert.present();
  }
}
