import {Component, Inject} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
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 {PermissionGroup, PermissionGroupsService, PermissionsService} from '../../../../classes/resorcess/permissions.service';
import {ICollection} from 'ngx-jsonapi';
import {Base} from 'ngx-jsonapi/services/base';
import {setErrors} from '../../../../classes/utils';


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

export class EditRolesComponent extends EditComponent {
  public loading = false;
  nameCtrl = new FormControl('', [Validators.required]);
  slugCtrl = new FormControl('', [Validators.required]);
  permissionsCtrl = new FormControl('', [Validators.required]);
  form: FormGroup;
  role: Role;
  permissionGroups: ICollection<PermissionGroup> = Base.newCollection<PermissionGroup>();
  constructor(private fb: FormBuilder,
              public rolesService: RolesService,
              private permision: PermissionsService,
              private permissionGroupsService: PermissionGroupsService,
              protected  dialog: Dialog,
              public  dialogRef: MatDialogRef<EditRolesComponent>,
              @Inject(MAT_DIALOG_DATA)  data,
  ) {
    super();
    this.role = data;
    // fetch permissions lists
    this.permision.all({include: ['group']}).subscribe(
      x => {
        if (x.$source != 'server' || x.$is_loading)
          return;
      }
    );


    this.permissionGroupsService.all({include: ['permissions']})
      .subscribe(
        response => {
          if (response.$source != 'server' || response.$is_loading)
            return;
          for(let i =0 ; i<response.$toArray.length ; i++){

          }
          this.permissionGroups = response;
        },
        error => console.error('Could not load authors')
      );
    this.form = this.fb.group({
      slugCtrl: this.slugCtrl,
      nameCtrl: this.nameCtrl,
      permissionsCtrl: this.permissionsCtrl,
    });
  }

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

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





