import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {Router} from '@angular/router';
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 {Component, Inject} from '@angular/core';
import {Permission, PermissionGroupsService} from '../../../../classes/resorcess/permissions.service';
import {setErrors} from '../../../../classes/utils';

@Component({
  selector: 'app-edit-permissions',
  templateUrl: './edit-permissions.component.html',
  styleUrls: ['./edit-permissions.component.scss']
})
export class EditPermissionsComponent {
  public loading = false;
  nameCtrl = new FormControl('', [Validators.required]);
  slugCtrl = new FormControl('', [Validators.required]);
  groupCtrl = new FormControl('', [Validators.required]);
  form: FormGroup;
  group;
  permission: Permission;


  constructor(private fb: FormBuilder,
              private roleService: RolesService,
              private router: Router,
              private PermissiongroupsService: PermissionGroupsService,
              protected  dialog: Dialog,
              public  dialogRef: MatDialogRef<EditPermissionsComponent>,
              @Inject(MAT_DIALOG_DATA)  data) {
    PermissiongroupsService.register();
    this.permission = data;
    const basics = JSON.parse(localStorage.getItem('basics'));
    this.group = basics['permission_groups'];
    this.PermissiongroupsService.all({include: ['permissions']}).subscribe(x =>{
    })

    this.form = this.fb.group({
      slugCtrl: this.slugCtrl,
      nameCtrl: this.nameCtrl,
      groupCtrl: this.groupCtrl,
    });
  }


  onSubmit() {
    this.loading = true;
    if (!this.form.valid) {
      console.log(this.form.valid);
      this.loading = false;
      return;
    }
    this.permission.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); //test
  }


}





