import {Component, OnInit, ViewChild} from '@angular/core';
import {Router} from '@angular/router';
import {FormBuilder, FormGroup, Validators, FormControl} from '@angular/forms';
import {HttpClient} from '@angular/common/http';
import {AuthService} from '../../../classes/servicess/auth.service';
import {Dialog} from '../../../classes/base_components/dialog/dialog';
import {repairErrors, setErrors} from '../../../classes/utils';

@Component({
  selector: 'app-signin',
  templateUrl: './passwordSignin.component.html',
  styleUrls: ['./passwordSignin.component.scss']
})
export class PasswordSigninComponent implements OnInit {
  public loading = false;
  passwordCtrl = new FormControl('', [Validators.required]);
  type;
  mobileCtrl = new FormControl('', [Validators.required, Validators.minLength(4)]);
  public form: FormGroup;
  remember: boolean = false;

  /**
   * @param {FormBuilder} fb marbot be form
   * @param {Router} router baray navigate kardan hast
   * @param {HttpClient} http baray darkhast hay http estefade mishe
   * @param {AuthService} auth baray moshakhas kardan inke login hast ya na
   */
  constructor(
    private fb: FormBuilder,
    private router: Router,
    private http: HttpClient,
    private auth: AuthService,
    private dialog: Dialog,
  ) {
  }

  ngOnInit() {
    this.form = this.fb.group({
      passwordCtrl: this.passwordCtrl,
      mobileCtrl: this.mobileCtrl,
    });
  }

  onSubmit() {
    this.loading = true;
    this.auth.loginWithPassword(this.form.controls['mobileCtrl'].value, this.form.controls['passwordCtrl'].value
      , this.remember, '1', '1', '1')
      .subscribe(
        loggedIn => {
          if (loggedIn) {
            this.loading = false;
            this.router.navigateByUrl('/');
          }
        },
        error => {
          this.loading = false;
          let errors = error.json().errors;
          setErrors(repairErrors(errors), this.form.controls, this.dialog);
        });
  }
}


