import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router, ActivatedRoute } from '@angular/router';
import { UpdateUserDetails, UpdatePassword } from '../../config/services/user';
import { UpdateService } from '../../config/update.service';
import { ServiceService } from '../../config/service.service';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-changedetails',
  templateUrl: './changedetails.page.html',
  styleUrls: ['./changedetails.page.scss']
})
export class ChangedetailsPage implements OnInit {
  userData: any;
  updateData: UpdateUserDetails = {
    phoneVerified: false,
    phone: ''
  };
  confPasswordErr: string;

  updatePassword: UpdatePassword = {
    password: '',
    confirmPassword: ''
  };
  submitted = false;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private location: Location,
    public register: UpdateService,
    private service: ServiceService
  ) {
    // Gets userdata
    this.service.get('userData').then(val => {
      console.log(JSON.parse(val));
      this.userData = JSON.parse(val);
      console.log(this.userData);
    });

    // this.service.get('user').then(data => {
    //   if (data) {
    //     this.userData = JSON.parse(data);
    //     console.log(this.userData);
    //   }
    // });
  }

  ngOnInit() { }

  goToPage(path, data = null) {
    this.router.navigateByUrl(path, { queryParams: data });
    document.body.scrollTop = document.documentElement.scrollTop = 0;
  }

  goBack() {
    this.location.back();
  }

  onFormSubmit(form: NgForm) {
    this.submitted = true;
    console.log(form.value);
    // if (form.valid) {
    // Change Password
    if (
      form.value.currentPassword &&
      form.value.password &&
      form.value.password === form.value.confirmPassword
    ) {
      this.register.updateData(form.value, this.userData);
      this.register.updatePassword(
        form.value.currentPassword,
        form.value.password
      );
    } else {
      this.register.updateData(form.value, this.userData);
      console.log('profile updated', form.value);
    }
  }
}
