import * as tslib_1 from "tslib";
import { Injectable } from '@angular/core';
import { auth } from 'firebase/app';
import { Router } from '@angular/router';
import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFirestore } from '@angular/fire/firestore';
import { ServiceService } from './../config/service.service';
import { SubjectService } from './../config/subject.service';
import { GooglePlus } from '@ionic-native/google-plus/ngx';
import { take } from 'rxjs/operators';
let AuthService = class AuthService {
    constructor(afs, afAuth, router, service, subjectService, googlePlus) {
        this.afs = afs;
        this.afAuth = afAuth;
        this.router = router;
        this.service = service;
        this.subjectService = subjectService;
        this.googlePlus = googlePlus;
        this.loader = true;
        this.type = 1;
        this.afAuth.authState.subscribe(user => {
            console.log('here');
            console.log(user);
            if (user) {
                this.subjectService.sendLoginData(false);
                this.userData = user;
                console.log(this.userData);
                this.service.set('user', JSON.stringify(this.userData));
                this.SetUserData(user);
                this.loader = false;
                if (this.type === 1) {
                    this.router.navigateByUrl('home', { replaceUrl: true });
                }
                else {
                    this.router.navigateByUrl('verification');
                }
            }
            else {
                console.log('here too');
                this.loader = false;
                this.subjectService.sendLoginData(true);
                this.service.set('user', null);
                JSON.parse(localStorage.getItem('user'));
                this.router.navigateByUrl('login', { replaceUrl: true });
            }
        });
    }
    checkLogin() {
        this.afAuth.authState.subscribe(user => {
            if (!user) {
                this.router.navigateByUrl('login', { replaceUrl: true });
            }
        });
    }
    get isLoggedIn() {
        const user = JSON.parse(localStorage.getItem('user'));
        return user !== null && user.emailVerified !== false ? true : false;
    }
    SignIn(email, password) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            this.loader = true;
            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 => {
                this.loader = false;
                this.service.showToast(error.message, 'bottom', 'my-error', 1000);
            });
        });
    }
    verify(otp) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            this.loader = true;
            const custRef = this.afs.collection('customers', ref => ref.where('otp', '==', otp).where('uid', '==', this.userData.uid));
            custRef
                .valueChanges()
                .pipe(take(1))
                .subscribe((value) => {
                if (value.length > 0) {
                    this.afs
                        .collection('customers')
                        .doc(this.userData.uid)
                        .update({ otp: '', phoneVerified: true });
                    this.service.set('type', 1);
                    this.loader = false;
                    this.router.navigateByUrl('nearby');
                }
                else {
                    this.loader = false;
                    this.service.showToast('Please input valid OTP', 'bottom', 'my-error', 1000);
                }
            });
        });
    }
    profilePic(pic) {
        this.afs
            .collection('customers')
            .doc(this.userData.uid)
            .update({ profilePhoto: pic });
    }
    google(type) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            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.additionalUserInfo.isNewUser);
                if (result.additionalUserInfo &&
                    result.additionalUserInfo.isNewUser === true) {
                    this.socialSignUp(result);
                }
            })
                .catch(err => {
                console.log(err);
                this.loader = false;
                console.log(this.loader);
            });
        });
    }
    facebook(type) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            this.type = type;
            const This = this;
            setTimeout(() => {
                This.loader = false;
            }, 3000);
            try {
                this.afAuth.auth
                    .signInWithPopup(new auth.FacebookAuthProvider())
                    .then(result => {
                    /* this.loader = false;
                    console.log('success');
                    console.log(result); */
                    console.log('success');
                    console.log(result.additionalUserInfo.isNewUser);
                    if (result.additionalUserInfo &&
                        result.additionalUserInfo.isNewUser === true) {
                        this.socialSignUp(result);
                    }
                })
                    .catch(err => {
                    this.service.showToast(err.message, 'bottom', 'my-error', 1000);
                });
            }
            catch (error) {
                This.loader = false;
            }
        });
    }
    SetUserData(user) {
        const userRef = this.afs.doc(`customers/${user.uid}`);
        userRef.valueChanges().subscribe(value => {
            console.log(value);
            const userData = {
                uid: value.uid,
                emailId: value.emailId,
                name: value.name,
                dob: value.dob,
                profilePhoto: value.profilePhoto,
                emailVerified: value.emailVerified,
                phone: value.phone,
                phoneVerified: value.phoneVerified,
                status: value.status,
                currency: value.currency,
                otp: value.otp,
                loginType: value.loginType
            };
            this.loggedUser = userData;
            this.service.set('userData', JSON.stringify(this.loggedUser));
            this.subjectService.sendUserData(JSON.stringify(this.loggedUser));
            console.log(this.loggedUser);
        });
    }
    SignOut() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            this.loader = true;
            return this.afAuth.auth.signOut().then(() => {
                this.service.clear();
                this.subjectService.sendLoginData(true);
                this.loader = false;
                console.log('logout');
            });
        });
    }
    socialSignUp(userData) {
        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 = {
            uid: userData.uid,
            status: true,
            dob: userData.dob ? userData.dob : '',
            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) {
        this.loader = true;
        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 dobDate = new Date(userData.dob);
            const postData = {
                uid: custData.uid,
                dob: dobDate.toDateString(),
                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');
                this.service.set('userData', JSON.stringify(postData));
            });
            this.loader = false;
        })
            .catch(error => {
            this.loader = false;
            window.alert(error.message);
        });
    }
    createAddress(addressData) {
        console.log(addressData);
        console.log(this.userData.uid);
        this.loader = true;
        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', { replaceUrl: true });
                document.body.scrollTop = document.documentElement.scrollTop = 0;
            })
                .catch(err => {
                this.loader = false;
            });
            this.loader = false;
        });
        return false;
    }
    resetPassword(email) {
        this.loader = true;
        this.afAuth.auth.sendPasswordResetEmail(email)
            .then(() => {
            this.service.showToast('Password reset mail has been sent your mail Id', 'top', 'my-toast', 2000);
            this.loader = false;
            this.router.navigateByUrl('login', { replaceUrl: true });
        })
            .catch((error) => {
            this.service.showToast(error, 'top', 'my-error', 1000);
            this.loader = false;
        });
    }
};
AuthService = tslib_1.__decorate([
    Injectable({
        providedIn: 'root'
    }),
    tslib_1.__metadata("design:paramtypes", [AngularFirestore,
        AngularFireAuth,
        Router,
        ServiceService,
        SubjectService,
        GooglePlus])
], AuthService);
export { AuthService };
//# sourceMappingURL=auth.service.js.map