import { Injectable } from "@angular/core";
import {
  User,
  UpdateUserDetails,
  Address,
  updatePassword
} 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 UpdateService {
  userData: any;
  type: number;
  userPostData: any;
  updateStatus: number;

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

  updateData(userData: UpdateUserDetails, uid: string) {
    this.type = 2;

    const postData: UpdateUserDetails = {
      phone: userData.phone,
      name: userData.name,
      emailId: userData.emailId
    };
    this.userPostData = postData;

    this.afs
      .collection("customers")
      .doc(uid)
      .update(postData)
      .then(() => {
        console.log("success");
        this.router.navigateByUrl("profile");
      })
      .catch(error => {
        console.log(error);
      });
  }

  // Change Password
  updatePassword(userData: updatePassword) {
    // Gets current user
    let user = this.afAuth.auth.currentUser;
    let newPassword = userData.password;

    // Update password
    user
      .updatePassword(newPassword)
      .then(() => {
        console.log("Password Changed");
      })
      .catch(err => {
        console.log(err);
      });
  }
}
