import { Component } from '@angular/core';
import { Platform, NavController, LoadingController, AlertController, Events } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { AuthService } from './services/auth.service';
import { LanguageService } from './services/language.service';
import { AlertService } from './services/alert.service';
import { TranslateService } from '@ngx-translate/core';
import { User } from 'src/app/models/user';
import { OneSignal, OSNotificationPayload } from '@ionic-native/onesignal/ngx';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html'
})
export class AppComponent {

  private loading;

  public appPages = [];

  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    private authService: AuthService,
    private languageService: LanguageService,
    private translateService: TranslateService,
    private navCtrl: NavController,
    private events: Events,
    private alertService: AlertService,
    private oneSignal: OneSignal,
    private iab: InAppBrowser,
    private loadingCtrl: LoadingController,
  ) {
    this.initializeApp();
    this.events.subscribe('set_role', role => {
      if (role >= 2){
        this.appPages = [
          {
            title: this.translateService.instant('menu.home'),
            url: '/dashboard',
            icon: 'home'
          },
          {
            title: this.translateService.instant('menu.cards'),
            url: '/cards',
            icon: 'card'
          },
          {
            title: this.translateService.instant('menu.postulations'),
            url: '/postulations',
            icon: 'hammer'
          },
          {
            title: this.translateService.instant('menu.contracts'),
            url: '/contracts',
            icon: 'filing'
          },
          {
            title: this.translateService.instant('menu.faq'),
            url: '/faq',
            icon: 'information-circle'
          },
          {
            title: this.translateService.instant('menu.start'),
            url: '/start',
            icon: 'send'
          }
        ];
      } else {
        this.appPages = [
          {
            title: this.translateService.instant('menu.home'),
            url: '/dashboard',
            icon: 'home'
          },
          {
            title: this.translateService.instant('menu.cards'),
            url: '/cards',
            icon: 'card'
          },
          {
            title: this.translateService.instant('menu.contracts'),
            url: '/contracts',
            icon: 'filing'
          },
          {
            title: this.translateService.instant('menu.faq'),
            url: '/faq',
            icon: 'information-circle'
          },
          {
            title: this.translateService.instant('menu.hero'),
            url: '/hero',
            icon: 'ribbon'
          }
        ];
      }
    });
  }
  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleLightContent();
      this.statusBar.overlaysWebView(false);
      // set status bar to white
      this.statusBar.backgroundColorByHexString('#0080ff');
      // Commenting splashScreen Hide, so it won't hide splashScreen before auth check
      //this.splashScreen.hide();
      this.languageService.getDefaultLanguage();
      this.authService.getToken();
      this.handlerNotifications();

    });
  }

  // When Logout Button is pressed
  logout() {
    this.loadingCtrl.create().then((overlay) => {
      this.loading = overlay;
      this.loading.present();
    });
    this.authService.logout().subscribe(
      data => {
        this.alertService.presentToast(this.translateService.instant('alerts.logout'));
        this.oneSignal.sendTag("iChamba_ID", null);
      },
      error => {
        this.loading.dismiss();
        console.log(error);
      },
      () => {
        this.loading.dismiss();
        this.navCtrl.navigateRoot('/landing');
      }
    );
  }

  openUrl(url) {
    this.iab.create(url, '_system')
  }

  private handlerNotifications(){
    this.oneSignal.startInit('00d23dae-1209-42cc-bea7-e1f17cee27fa', '679874302148');
      this.oneSignal.inFocusDisplaying(this.oneSignal.OSInFocusDisplayOption.Notification);
      this.oneSignal.handleNotificationReceived().subscribe(data => this.onPushReceived(data.payload));
      this.oneSignal.handleNotificationOpened().subscribe(data => this.onPushOpened(data.notification.payload));
      this.oneSignal.endInit();
  }

  private onPushReceived(payload: OSNotificationPayload) {
  	this.alertService.presentAlert(payload.title, payload.body, ['OK']);
    if (payload.title == 'Proveedor: hay nueva postulación' || payload.title == 'Hero: there is a new postulation') {
      this.navCtrl.navigateRoot('/postulations');
      this.events.publish('refreshpostulations', 'data');
    } else if (payload.title == 'Búsqueda Finalizada' || payload.title == 'Search finished') {
      this.navCtrl.navigateRoot('/contracts');
    } else if (payload.title == 'Usuario: el proveedor ha iniciado el servicio' || payload.title == 'User: the Hero has started the service') {
      this.navCtrl.navigateRoot('/contracts');
    }

  }

  private onPushOpened(payload: OSNotificationPayload) {
    if (payload.title == 'Proveedor: hay nueva postulación' || payload.title == 'Hero: there is a new postulation') {
      this.navCtrl.navigateRoot('/postulations');
      this.events.publish('refreshpostulations', 'data');
    } else if (payload.title == 'Búsqueda Finalizada' || payload.title == 'Search finished') {
      this.navCtrl.navigateRoot('/contracts');
    } else if (payload.title == 'Usuario: el proveedor ha iniciado el servicio' || payload.title == 'User: the Hero has started the service') {
      this.navCtrl.navigateRoot('/contracts');
    }
  }
}
