import { Component, OnInit } from '@angular/core';
import {AuthService} from '../service/auth.service';
import {PeopleService} from '../service/people.service';
import {FormControl, FormGroup} from '@angular/forms';

@Component({
  selector: 'app-settings',
  templateUrl: './settings.component.html',
  styleUrls: ['./settings.component.scss']
})
export class SettingsComponent implements OnInit {
  public changeAdminPassword = false;
  public opened = false; // dialog box
  public Message = '';   // dialog message

  public ChangeAdminPassForm: FormGroup = new FormGroup({
    OldPassword: new FormControl(),
    NewPass: new FormControl(),
    NewPass1: new FormControl(),
  });
  constructor(private auth: AuthService, private ps: PeopleService) { }

  ngOnInit(): void {
    setTimeout(() => {
      this.changeAdminPassword = true;
    }, 1000);
  }


  public hideAdminPass(): void{
    if ( this.changeAdminPassword ) {
      this.ChangeAdminPassForm.reset();
    }
  }

  public saveAdminPassword(): void{
    this.ps.savePassword('0', this.ChangeAdminPassForm.value).subscribe(
      () => {
        this.showDialog('Password Changed');
      }, err => {
        this.showDialog('Failed to Change Password :' + err.toString());
      }
    );
  }

  public adminPasswordEqual(): boolean{
    const v = this.ChangeAdminPassForm.value;
    if ( this.ChangeAdminPassForm.valid && v.NewPass === v.NewPass1 && this.ChangeAdminPassForm.touched && v.NewPass1 !== '') {
      return true;
    }else{
      this.ChangeAdminPassForm.controls['NewPass1'].setErrors({'incorrect': true});
    }
    return false;
  }

  public showDialog(msg: string): void {
    this.Message = msg;
    this.opened = true; // open dialog
  }

  public close(status): void {
    this.opened = false;
  }
}
