import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import {ResetpasswordService} from './resetpassword.service';
import { ActivatedRoute, Router } from '@angular/router';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { ToastrService } from 'ngx-toastr';

@Component({
  selector: 'app-resetpassword',
  templateUrl: './resetpassword.component.html',
  styleUrls: ['./resetpassword.component.css']
})
export class ResetpasswordComponent implements OnInit {
  resetForm: FormGroup;
  postresult: boolean;
  email: string;
  userid: string;
  submitted = false;
  loading = false;
  error: string;
  anio: number = new Date().getFullYear();
  constructor(
    private formBuilder: FormBuilder,
    private resetservice: ResetpasswordService,
    private route: ActivatedRoute,
    private toastr: ToastrService,
     private router: Router
  ) { }

  ngOnInit() {
    this.resetForm = this.formBuilder.group({
      newpassword: ['', Validators.required],
      confirmpassword: ['', Validators.required]
    });
    this.email = this.route.snapshot.queryParamMap.get('email');
  }

  get f() { return this.resetForm.controls; }

  onSubmit(http: HttpClient) {
    this.submitted = true;
    this.loading = true;
    if (this.f.newpassword.value !== this.f.confirmpassword.value) {
      this.toastr.error('Confirm password and new password should be same');
      return;
    }
    this.resetservice.resetpassword(this.f.newpassword.value, this.email).subscribe(res => {
      if (res.status === 200) { this.postresult = true; this.ngOnInit(); }
      this.toastr.success('Password Reset has been done successfully');
      this.router.navigate(['/login']);
    },
      error => {
        this.toastr.error('Password not changed.Some unexpected error.');
        this.postresult = false;
        this.error = error.error;
      });
    this.loading = false;
  }
}
