import { Injectable } from '@angular/core';
import { User, Signup, Address } from './services/user';
import { auth } from 'firebase/app';
import { Router, ActivatedRoute } from '@angular/router';
import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFirestore, AngularFirestoreDocument, AngularFirestoreCollection } from '@angular/fire/firestore';
import { ServiceService } from './../config/service.service';
import { GooglePlus } from '@ionic-native/google-plus/ngx';
import { take } from 'rxjs/operators';
import { from } from 'rxjs';

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

  constructor(
    public afs: AngularFirestore,
    public afAuth: AngularFireAuth,
    private router: Router,
    private service: ServiceService,
    private googlePlus: GooglePlus
  ) {
      this.type = 1;
      this.afAuth.authState.subscribe(user => {
        if (user) {
          this.userData = user;
          console.log(this.userData);
          this.service.set('user', JSON.stringify(this.userData));
          if (this.type === 1) {
            this.router.navigateByUrl('home');
          } else {
           this.router.navigateByUrl('verification');
          }
        } else {
          this.service.set('user', null);
          JSON.parse(localStorage.getItem('user'));
          this.router.navigateByUrl('login');
        }
      });
  }

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

  public async verify(otp: string) {
    console.log(this.userData.uid, otp);
    // tslint:disable-next-line:radix
    // const otpnew = parseInt(otp);
    const custRef: AngularFirestoreCollection<any> = this.afs.collection('customers', ref => ref.where('otp', '==', otp)
    .where('uid', '==', this.userData.uid)
    );
    custRef.valueChanges().pipe(take(1)).subscribe((value: User[]) => {
      if (value.length > 0) {
        this.afs.collection('customers').doc(this.userData.uid).update({otp: ''});
        this.router.navigateByUrl('addaddresss');
      } else {
        window.alert('Please input valid OTP');
      }
    });

  }


  public async google(type: number) {
    this.type = type;
    // this.googlePlus.login({}).then(res => console.log(res)).catch(err => console.error(err));
    this.afAuth.auth.signInWithPopup(new auth.GoogleAuthProvider()).then((result) => {
      console.log('success');
      console.log(result);
      this.socialSignUp(result);
    });
  }

  public async facebook(type: number) {
    this.type = type;
    this.afAuth.auth.signInWithPopup(new auth.FacebookAuthProvider()).then((result) => {
      console.log('success');
      console.log(result);
    });
  }

  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,
        otp: value.otp,
        loginType: value.loginType
        };
      console.log(userData);
    });
  }

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

  socialSignUp(userData: any) {
    this.type = 2;
    console.log(userData.user);
    const currencyData = {
      currId: '123',
      currName: 'Australian dollar',
      symbol: 'A$'
    };
    const otp = Math.floor(1000 + Math.random() * 9000);
    userData = userData.user;
    const postData: User =  {
      uid: userData.uid,
      status: true,
      profilePhoto: userData.photoURL,
      phoneVerified: false,
      phone: userData.phoneNumber,
      name: userData.displayName,
      emailVerified: userData.emailVerified,
      emailId: userData.email,
      currency: currencyData,
      otp: otp.toString(),
      loginType: 1
    };
    this.userPostData = postData;
    console.log(postData);
    this.afs.collection('customers').doc(userData.uid).set(postData).then(() => {
      console.log('successs');
    });
  }

  signup(userData: Signup) {
    this.type = 2;
    console.log(userData);
    const otp = Math.floor(1000 + Math.random() * 9000);
    this.afAuth.auth.createUserWithEmailAndPassword(userData.emailId, userData.password).then((result) => {
      console.log(result.user);
      this.afAuth.auth.currentUser.sendEmailVerification();
      const currencyData = {
        currId: '123',
        currName: 'Australian dollar',
        symbol: 'A$'
      };
      const custData = result.user;
      const postData: User =  {
        uid: custData.uid,
        status: true,
        profilePhoto: '',
        phoneVerified: false,
        phone: userData.phone,
        name: userData.name,
        emailVerified: false,
        emailId: userData.emailId,
        currency: currencyData,
        otp: otp.toString(),
        loginType: 0
      };
      this.userPostData = postData;
      console.log(postData);
      this.afs.collection('customers').doc(custData.uid).set(postData).then(() => {
        console.log('successs');
      });
    }).catch((error) => {
      window.alert(error.message);
    });
  }

  createAddress(addressData: Address) {
    console.log(addressData);
    console.log(this.userData.uid);

    this.afs.collection('address').add({
      uid: this.userData.uid
    }).then((docRef) => {
      console.log(docRef);
      const addrData =  {
        uid: this.userData.uid,
        addressType: addressData.addressType,
        area: addressData.area,
        city: addressData.city,
        country: addressData.country,
        district: addressData.district,
        firstAddress: addressData.firstAddress,
        landmark: addressData.landmark,
        zip: addressData.zip,
        secondAddress: addressData.secondAddress,
        state: addressData.state,
        addrId: docRef.id,
        default: 1
      };
      const neworderId = docRef.id;
      console.log(addrData);
      this.afs.collection('address').doc(neworderId).set(addrData).then(() => {
        console.log('Address add Successfully');
        this.service.set('user', JSON.stringify(this.userData));
        this.router.navigateByUrl('home');
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    });
    return false;
  }
}


/*displayName: "Adarsh Techware"
email: "adarsh.techware@gmail.com"
emailVerified: true
: "https://lh4.googleusercontent.com/-h0rs2pE-Azw/AAAAAAAAAAI/AAAAAAAAAAA/ACHi3rcjNtapRhKoG09NKifQsv_lQPC_2A/photo.jpg"
: "vT498Fz6X0Z6l5l5iNn5hxfwz692"
providerData: [Gl]*/




