import { computed, makeObservable, observable } from 'mobx';
import { User } from './User';
import { ApphouseStore } from '../context/ApphouseStore';
import { FirebaseApp, initializeApp } from 'firebase/app';
import { Analytics, getAnalytics } from 'firebase/analytics';
import { ApphouseFirestore } from '..';

/**
 * The firebase configuration object
 * @see https://firebase.google.com/docs/web/setup#available-libraries
 */
export interface ApphouseFirebaseConfig {
  apiKey: string;
  authDomain: string;
  projectId: string;
  storageBucket: string;
  messagingSenderId: string;
  appId: string;
  measurementId: string;
}
/**
 * AppStoreWithUser for ApphouseStore that handles the user authentication
 * and authorization using firebase authentication
 */
export class AppStoreWithUser extends ApphouseStore {
  user: User;
  analytics: Analytics;
  firebase: FirebaseApp;
  api: ApphouseFirestore<string>;

  constructor(firebaseConfig: ApphouseFirebaseConfig, onSignOut?: () => void) {
    super('apphouse');
    // Initialize Firebase
    this.firebase = initializeApp(firebaseConfig);
    this.analytics = getAnalytics(this.firebase);

    this.user = new User(() => {
      // on log out
      this.app.feedback.setFeedback({
        message: 'You have signed out successfully',
        variant: 'info'
      });
      if (onSignOut) {
        onSignOut();
      } else {
        // redirect to home page
        this.app.view.open('/');
      }
    });
    this.user.initFirebase();
    this.api = new ApphouseFirestore(this.user, this.app.feedback);

    makeObservable(this, {
      user: observable,
      isAuthorized: computed
    });
  }

  get isAuthorized() {
    return this.user?.authorized;
  }
}
