import { Injectable } from '@angular/core';
import { User } from './services/user';
import { auth } from 'firebase/app';
import { Router, ActivatedRoute } from '@angular/router';
import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';
import { ServiceService } from './../config/service.service';
import { from } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  userData: any;

  constructor(
    public afs: AngularFirestore,
    public afAuth: AngularFireAuth,
    private router: Router,
    private service: ServiceService
  ) {
      this.afAuth.authState.subscribe(user => {
        if (user) {
          this.userData = user;
          this.service.set('user', JSON.stringify(this.userData));
        } else {
          this.service.set('user', null);
          JSON.parse(localStorage.getItem('user'));
        }
      });
  }

  public async SignIn(email: string, password: string) {
    return this.afAuth.auth.signInWithEmailAndPassword(email, password).then((result) => {
      console.log('success');
      this.router.navigateByUrl('home');
      document.body.scrollTop = document.documentElement.scrollTop = 0;
      this.SetUserData(result.user);
    }).catch((error) => {
      window.alert(error.message);
    });
  }

  get isLoggedIn(): boolean {
    const user = JSON.parse(localStorage.getItem('user'));
    return (user !== null && user.emailVerified !== false) ? true : false;
  }

  SetUserData(user: any) {

    const userRef: AngularFirestoreDocument<any> = this.afs.doc(`customers/${user.uid}`);
    userRef.valueChanges().subscribe((value) => {
      const userData: User = {
        uid: value.uid,
        emailId: value.emailId,
        name: value.name,
        profilePhoto: value.profilePhoto,
        emailVerified: value.emailVerified,
        phone: value.phone,
        phoneVerified: value.phoneVerified,
        status: value.status,
        currency: value.currency
        };
      console.log(userData);
    });
  }

  public async SignOut() {
    return this.afAuth.auth.signOut().then(() => {
      this.service.remove('user');
      console.log('logout');
    });
  }


}
