/**
 * React Native Full App (https://store.enappd.com/product/react-native-full-app)
 *
 * Copyright © 2019-present Enappd. All rights reserved.
 *
 * This source code is licensed as per the terms found in the
 * LICENSE.md file in the root directory of this source tree.
 */

import app from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
import 'firebase/storage';

const config = {
  apiKey: 'AIxxxxxxxxxLC_oFgWCNDDSqNw3Y7Rl_liwo',
  authDomain: 'react-learning-dc154.firebaseapp.com',
  databaseURL: 'https://react-learning-dc154.firebaseio.com',
  projectId: 'react-learning-dc154',
  storageBucket: 'ionic4fullapp.appspot.com',
  messagingSenderId: '6678xxxx468',
};

class Firebase {
  auth: app.auth.Auth;
  firestore: app.firestore.Firestore;
  storage: app.storage.Storage;

  constructor() {
    if (!app.apps.length) {
      app.initializeApp(config);
    }

    this.auth = app.auth();
    this.firestore = app.firestore();
    this.storage = app.storage();

    console.ignoredYellowBox = ['Setting a timer'];
  }

  // Authentication Operations functions section
  signUpWithEmailAndPassword = (
    email: string,
    password: string
  ): Promise<any> => {
    return this.auth.createUserWithEmailAndPassword(email, password);
  };
  signInWithEmailAndPassword = (
    email: string,
    password: string
  ): Promise<any> => {
    return this.auth.signInWithEmailAndPassword(email, password);
  };
  signOut = (): Promise<void> => this.auth.signOut();

  passwordReset = (email: string): Promise<void> =>
    this.auth.sendPasswordResetEmail(email);

  passwordUpdate = (password: string): Promise<void> =>
    this.auth.currentUser.updatePassword(password);

  getCurrentUserId = (): any =>
    this.auth.currentUser ? this.auth.currentUser.uid : null;

  //User Data Interection function section
  createNewUser = (userData: any): Promise<void> =>
    this.firestore.doc(`users/${userData.uid}`).set(userData);

  checkUserExists = (userId: string): Promise<any> =>
    new Promise((resolve, reject) => {
      this.firestore
        .collection('users')
        .doc(userId)
        .get()
        .then((doc) => {
          const { exists } = doc;
          resolve(exists);
        })
        .catch((e) => reject(e));
    });

  //CURD Operations functions section
  getQuestionsList = () =>
    this.firestore
      .collection('Faq')
      .where('userId', '==', this.auth.currentUser.uid);

  addNewQuestion = (dataToStore: any): Promise<any> =>
    this.firestore.collection('Faq').add(dataToStore);

  getOne = (docId: string): Promise<any> =>
    this.firestore.doc(`Faq/${docId}`).get();

  updateQuestion = (dataToUpdate: any): Promise<void> =>
    this.firestore.doc(`Faq/${dataToUpdate.id}`).update(dataToUpdate);

  removeQuestion = (docId: string): Promise<void> =>
    this.firestore.doc(`Faq/${docId}`).delete();

  // Upload image functions section
  uploadImage = (imageBlob: any): Promise<any> =>
    new Promise((resolve, reject) => {
      const fileName = new Date().getTime().toString();
      const userId = this.auth.currentUser.uid;
      const ref = this.storage.ref(`uploads/${userId}`).child(fileName);
      ref
        .put(imageBlob)
        .then(() =>
          ref.getDownloadURL().then((url) => {
            this.firestore
              .collection('imageReference')
              .add({ url, userId })
              .then((imageData) => resolve({ id: imageData.id }))
              .catch((e) => reject(e));
          })
        )
        .catch((e) => reject(e));
    });

  getImagesList = () =>
    this.firestore
      .collection('imageReference')
      .where('userId', '==', this.auth.currentUser.uid);

  updateImageRef = (dataToUpdate: any): Promise<void> =>
    this.firestore
      .doc(`imageReference/${dataToUpdate.id}`)
      .update(dataToUpdate);

  removeImage = (imageId: string): Promise<void> =>
    this.firestore.doc(`imageReference/${imageId}`).delete();

  // social login

  loginWithFacebook = (token: string): Promise<any> => {
    const credential = app.auth.FacebookAuthProvider.credential(token);
    return this.auth.signInAndRetrieveDataWithCredential(credential);
  };
}

export default Firebase;
