import 'package:aitrainer_app/model/cache.dart';
import 'package:aitrainer_app/service/logging.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
//import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';

class FirebaseApi with Logging {
  static FirebaseApi _instance;

  static final FirebaseAuth auth = FirebaseAuth.instance;

  static const String SIGN_IN_OK = "OK";
  static const String SIGN_IN_NOT_FOUND = "user-not-found";
  static const String SIGN_IN_WRONG_PWD = "wrong-password";
  static const String REGISTER_WEAK_PWD = "weak-password";
  static const String REGISTER_EMAIL_IN_USE = "email-already-in-use";

  UserCredential userCredential;

  factory FirebaseApi() => _instance ?? FirebaseApi._internal();

  FirebaseApi._internal() {
    _instance = this;
  }

  // Define an async function to initialize FlutterFire
  Future<void> initializeFlutterFire() async {
    try {
      // Wait for Firebase to initialize and set `_initialized` state to true
      await Firebase.initializeApp();
    } catch (e) {
      // Set `_error` state to true if Firebase initialization fails
      log("Error initializing Firebase");
    }
  }

  Future<String> signInEmail(String email, String password) async {
    String rc = SIGN_IN_OK;
    try {
      userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword(email: email, password: password);
      Cache().firebaseUid = userCredential.user.uid;
    } on FirebaseAuthException catch (e) {
      if (e.code == 'user-not-found') {
        log('No user found for that email.');
        rc = SIGN_IN_NOT_FOUND;
      } else if (e.code == 'wrong-password') {
        log('Wrong password provided for that user.');
        rc = SIGN_IN_WRONG_PWD;
        throw Exception("Customer does not exist or the password is wrong");
      }
      return e.code;
    }
    return rc;
  }

  Future<String> registerEmail(String email, String password) async {
    String rc = SIGN_IN_OK;
    try {
      userCredential = await FirebaseAuth.instance.createUserWithEmailAndPassword(email: email, password: password);
      Cache().firebaseUid = userCredential.user.uid;
    } on FirebaseAuthException catch (e) {
      if (e.code == 'weak-password') {
        log('The password provided is too weak.');
        rc = REGISTER_WEAK_PWD;
        throw Exception("Password too short");
      } else if (e.code == 'email-already-in-use') {
        log('The account already exists for that email.');
        rc = REGISTER_EMAIL_IN_USE;
        throw Exception("The email address has been registered already");
      }
    } catch (e) {
      log(e);
      throw Exception(e.toString());
    }
    return rc;
  }

  /*Future<UserCredential> signInWithFacebook() async {
    // Trigger the sign-in flow
    final LoginResult result = await FacebookAuth.instance.login();

    // Create a credential from the access token
    final FacebookAuthCredential facebookAuthCredential = FacebookAuthProvider.credential(result.accessToken.token);

    // Once signed in, return the UserCredential
    return await FirebaseAuth.instance.signInWithCredential(facebookAuthCredential);
  }*/

  Future<void> signOut() async {
    await FirebaseAuth.instance.signOut();
  }

  Future<void> resetPassword(String email) async {
    await FirebaseAuth.instance.sendPasswordResetEmail(email: email);
  }
}