import {Component, Inject, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {FormBuilder, FormGroup, Validators, FormControl} from '@angular/forms';
import {CustomValidators} from 'ng2-validation';
import {Dialog} from '../../../public/dialog';
import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material';
import {User} from '../../../public/services/user.service';

const password = new FormControl('', Validators.required);
const confirmPassword = new FormControl('', CustomValidators.equalTo(password));

@Component({
  selector: 'app-signup',
  templateUrl: './signup.component.html',
  styleUrls: ['./signup.component.scss']
})
export class SignupComponent {
  public loading = false;
  user: User;
  nameCtrl = new FormControl('', [Validators.required]);
  emailCtrl = new FormControl('', [Validators.required]);
  passwordCtrl = new FormControl('', [Validators.required]);
  mobileCtrl = new FormControl('', [Validators.required]);
  form: FormGroup;

  constructor(private fb: FormBuilder,
              private router: Router,
              protected  dialog: Dialog,
              public  dialogRef: MatDialogRef<SignupComponent>
  ) {

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

  onSubmit() {
    this.loading = true;
    this.user.setName(this.form.controls['nameCtrl'].value);
    this.user.setEmail(this.form.controls['emailCtrl'].value);
    this.user.setMobile(this.form.controls['mobileCtrl'].value);
    this.user.setPassword(this.form.controls['passwordCtrl'].value);
    this.user.save({},
      () => {
        this.loading = false;
        this.close();
      },
      (error) => {
        this.loading = false;
        const JsonV = error.errors;
        for (const key in JsonV) {
          if (key in JsonV) {
            const err = JsonV[key];
            const errorKey = (err.source.pointer).split('\/').reverse()[0] + 'Ctrl';
            this.form.controls[errorKey].setErrors({'error': err.detail});
          }
        }
      });

  }

  close() {
    this.dialogRef.close(true);
  }
}
