import { Injectable } from '@angular/core';
import { User, UpdateUserDetails, 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 { SubjectService } from './../config/subject.service';
import { GooglePlus } from '@ionic-native/google-plus/ngx';
import { take } from 'rxjs/operators';
import { from } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class UpdateService {
  userData: any;
  type: number;
  userPostData: any;
  updateStatus: number;
  loader: boolean;

  constructor(
    public afs: AngularFirestore,
    public afAuth: AngularFireAuth,
    private router: Router,
    private service: ServiceService,
    private subject: SubjectService
  ) {
    // 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");
    //   }
    // });
  }

  // Update User Data
  updateData(userData: UpdateUserDetails, oldData: User) {
    this.loader = true;
    this.type = 2;

    const postData: UpdateUserDetails = {
      phone: userData.phone,
      phoneVerified: false
      // name: userData.name
    };
    const updateOldData = {
      ...oldData,
      phone: userData.phone
      // name: userData.name
    };
    this.userPostData = postData;

    this.afs
      .collection('customers')
      .doc(oldData.uid)
      .update(postData)
      .then(() => {
        this.service
          .set('userData', JSON.stringify(updateOldData))
          .then(res => {
            this.subject.sendUserData(JSON.stringify(updateOldData));
            console.log('success', updateOldData, res);
            this.service
              .showToast('Profile updated!', 'top', 'my-toast', 1000)
              .then(() => {
                this.router.navigateByUrl('profile');
                this.loader = false;
              });
          })
          .catch(err => console.log(err));
      })
      .catch(error => {
        console.log(error);
      });
  }

  // Change user password
  updatePassword(currentPassword: string, newPasswd: string) {
    this.loader = true;

    const currentUser = this.afAuth.auth.currentUser; // Gets current user
    // Credential is required for re-authentication
    const credential = auth.EmailAuthProvider.credential(
      currentUser.email,
      currentPassword
    );

    // Re-authenticate user
    currentUser
      .reauthenticateWithCredential(credential)
      .then(() => {
        currentUser
          .updatePassword(newPasswd) // Update password
          .then(success => {
            console.log('password changed');
            this.loader = false;
            this.service
              .showToast('Password Changed!', 'top', 'my-toast', 1000) // success toast
              .then(res => {
                this.router.navigateByUrl('profile');
                this.loader = false;
              });
          })
          .catch(error => {
            console.log('something fishy');
            this.service
              .showToast('Something went wrong', 'top', 'my-toast', 1000) // failure toast
              .then(res => {
                this.loader = false;
              });
          });
      })
      .catch(error => {
        console.log(error);
        this.service
          .showToast(error.message, 'top', 'my-error', 3000) // failure toast
          .then(res => {
            this.loader = false;
          });
      });
  }
}
