import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Storage } from "@ionic/storage";
import firebase from "firebase";

@Injectable()
export class AuthProvider {
  authProvider: any;

  constructor(public http: HttpClient, private storage: Storage) {
    console.log("Hello AuthProvider Provider");

    var config = {
      apiKey: "AIzaSyCMYjjtPPZak7wBBnh9sy8Yr3Fz1145MuM",
      authDomain: "hybridosn.firebaseapp.com",
      databaseURL: "https://hybridosn.firebaseio.com",
      storageBucket: "hybridosn.appspot.com"
    };
    firebase.initializeApp(config);

    this.authProvider = new firebase.auth.TwitterAuthProvider();
    this.authProvider.setCustomParameters({
      lang: "de"
    });
  }

  login() {
    return firebase
      .auth()
      .signInWithRedirect(this.authProvider)
      .then(() => firebase.auth().getRedirectResult())
      .then(this.setKeys);
  }

  logout() {
    this.storage.clear();
  }

  async isLoggedIn() {
    let accessToken = await this.storage.get("accessTokenKey");
    let accessTokenKey = await this.storage.get("accessTokenSecret");
    return accessToken && accessTokenKey;
  }

  setKeys = result => {
    this.storage.set("accessTokenKey", result.credential["accessToken"]);
    this.storage.set("accessTokenSecret", result.credential["secret"]);
    this.storage.set("userId", result.additionalUserInfo["profile"]["id"]);
  };
}
