import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Storage } from "@ionic/storage";
import firebase from "firebase";
import { TwitterApiProvider } from "../twitter-api/twitter-api";

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

  constructor(
    public http: HttpClient,
    private storage: Storage,
    private twitter: TwitterApiProvider
  ) {
    const 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)
      .then(() => this.twitter.initApi());
  }

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

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

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