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


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

export class EditUsersComponent extends EditComponent {
  form: FormGroup;
  user: User;
  nameCtrl = new FormControl('', [Validators.required]);
  mobileCtrl = new FormControl('', [Validators.required]);
  enableCtrl = new FormControl('', [Validators.required]);
  // todo porside shavad
  emailCtrl = new FormControl();
  passwordCtrl = new FormControl();
  roleCtrl = new FormControl();
  loading = false;
  roles: Role[];


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

  onSubmit() {
    console.log('slaam ');
    // if (!this.form.valid) {
    //   this.loading = false;
    //   return;
    // }
    this.user.save({},
      () => {
        this.dialog.closeAll();
      },
      (error) => {
        console.log('error', error);
        const JsonV = error.errors;
        setErrors(JsonV, this.form.controls, this.dialog);
      });
  }

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





