import {Component, Inject, Injectable} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {Router} from '@angular/router';
import {User, UsersService} from '../users.service';
import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material';
import {Role, RolesService} from '../../roles/roles.service';
import {Dialog} from '../../../../classes/dialog';
import {EditComponent} from '../../../../classes/base_components/edit/edit.component';
import {TypesService} from '../../../basic/types/types.service';
import {repairErrors, setErrors} from '../../../../classes/utils';


@Component({
  selector: 'app-edit-users',
  templateUrl: './edit-users.component.html',
  styleUrls: ['./edit-users.component.scss']
})

export class EditUsersComponent extends EditComponent {
  public loading = false;
  nameCtrl = new FormControl('', [Validators.required]);
  emailCtrl = new FormControl('', [Validators.required]);
  passwordCtrl = new FormControl('', [Validators.required]);
  mobileCtrl = new FormControl('', [Validators.required]);
  typesCtrl = new FormControl('', [Validators.required]);
  rolesCtrl = new FormControl('', [Validators.required]);
  form: FormGroup;
  user: User;
  types;
  roles;


  constructor(private fb: FormBuilder,
              private roleService: RolesService,
              private router: Router,
              private  typeService: TypesService,
              private usersService: UsersService,
              protected  dialog: Dialog,
              public  dialogRef: MatDialogRef<EditUsersComponent>,
              @Inject(MAT_DIALOG_DATA)  data
  ) {
    super();
    this.loading = false;
    const basics = JSON.parse(localStorage.getItem('basics'));
    this.types = basics['types'];
    this.roles = basics['roles'];
    this.user = data;
    this.form = this.fb.group({
      emailCtrl: this.emailCtrl,
      nameCtrl: this.nameCtrl,
      mobileCtrl: this.mobileCtrl,
      passwordCtrl: this.passwordCtrl,
      typesCtrl: this.typesCtrl,
      rolesCtrl: this.rolesCtrl,
    });
  }

  onSubmit(){
    this.loading = true;
    if (!this.form.valid) {
      this.loading = false;
      return;
    }
    this.user.save({},
      () => {
        this.loading = false;
        this.close();
      },
      (error) => {
        this.loading = false;
        const JsonV = error.errors;
        setErrors(JsonV, this.form.controls, this.dialog);
      });
  }

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





