import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { Device } from '@ionic-native/device';
import { StreamPage } from '../stream/stream';

import { OauthCordova } from 'ng2-cordova-oauth/platform/cordova';
import { OauthBrowser } from 'ng2-cordova-oauth/platform/browser';
import { PnutAuth } from '../../providers/pnut-oauth';
import * as pnut from 'pnut-butter';

/**
 * Generated class for the LoginPage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {

  private oauth: any;
  private pnutProvider: any;
  private oob: boolean = false;
  public showToken: boolean = false;
  private token: string;
  private scope: Array<string> = [];

  constructor(public navCtrl: NavController, public navParams: NavParams, private storage: Storage,
    private device: Device) {

    this.scope = navParams.data.scope;

    if (this.device.platform === "Android" || this.device.platform === "amazon-fireos") {
      this.oauth = new OauthCordova();
      this.pnutProvider = new PnutAuth({
        appScope: this.scope,
        redirectUri: 'http://localhost/callback'
      });
    } else if (this.device.platform === "blackberry10") {
      this.oauth = new OauthBrowser();
      this.pnutProvider = new PnutAuth({
        appScope: this.scope,
        redirectUri: 'https://zoidberg.monkeystew.net/'
      });
    } else {
      this.oauth = new OauthBrowser();
      this.pnutProvider = new PnutAuth({
        appScope: this.scope,
        redirectUri: 'urn:ietf:wg:oauth:2.0:oob'
      });
      this.oob = true;
    }

  }

  login() {
    this.oauth.logInVia(this.pnutProvider).then(success => {
      console.log('RESULT: ' + JSON.stringify(success));
      this.storage.set('token', success['access_token']);
      this.storage.set('scope', this.scope);
      pnut.token = success['access_token'];
      this.navCtrl.setRoot(StreamPage, {stream: 'personal'});
    }, error => {
      console.log(error);
      if (this.oob) {
        this.showToken = true;
      }
    });
  }

  saveToken() {
    this.storage.set('scope', this.scope);
    this.storage.set('token', this.token);
    pnut.token = this.token;
    this.navCtrl.setRoot(StreamPage, {stream: 'personal'});
  }

}
