import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ChangePasswordService } from './changepassword.service';
import { ToastrService } from 'ngx-toastr';
import { ActivatedRoute, Router } from '@angular/router';
@Component({
  selector: 'app-changepassword',
  templateUrl: './changepassword.component.html',
  styleUrls: ['./changepassword.component.css']
})
export class ChangepasswordComponent implements OnInit {
  changepsswordForm: FormGroup;
  postresult: boolean;
  userid: string;
  submitted = false;
  loading = false;
  constructor(private formBuilder: FormBuilder,
    private changeservice: ChangePasswordService,
    private toastr: ToastrService,
    private router: Router,
    private route: ActivatedRoute) { }
  ngOnInit() {
    this.changepsswordForm = this.formBuilder.group({
      oldpassword: ['', Validators.required],
      newpassword: ['', Validators.required],
      confirmpassword: ['', Validators.required]
    });
  }
  get f() { return this.changepsswordForm.controls; }
  onSubmit(user) {
    this.submitted = true;
    this.loading = true;
    const username = localStorage.getItem('emailid');
    if (user.newpassword !== user.confirmpassword) {
      this.toastr.error('Confirm password and new password should be same');
      return;
    }
    if (user.oldpassword === user.newpassword) {
      this.toastr.error('Old password and new password should not be same');
      return;
    }
    this.changeservice.checkoldpassword(user.oldpassword, username).subscribe(res => {

      if (res.status === 200) { this.postresult = true; this.changepassword(); }
    },
      error => {
        this.toastr.error(error.error);
        this.loading = false;
        return;
        this.postresult = false;
      });
  }

  changepassword() {
    const useridnew = localStorage.getItem('userid');
    this.changeservice.changepassword(this.f.newpassword.value, +useridnew).subscribe(res => {
      if (res.status === 200) {
        this.postresult = true;
        this.toastr.success('Password Reset has been done successfully');
        localStorage.clear();
        localStorage.removeItem('LoggedIn');
        this.router.navigate(['login']);
      }
    },
      error => {
        this.toastr.error(error.error);
        this.postresult = false;
      });
  }
}
