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 = {
    emailId: '',
    name: '',
    phone: ''
  };

  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('params').then(val => {
      this.userData = val;
      console.log(val);
    });
  }

  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.password &&
        form.value.password != form.value.confirmPassword
      ) {
        this.register.updatePassword(form.value.password);
      } else {
        alert('Password should match');
      }

      // Calls update user data fn
      this.register.updateData(form.value, this.userData.uid);
      console.log('valid form values', form.value);
    }
  }
}
