import {Component, ViewChild} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";
import {GroupService} from "../../services/group.service";
import {Router} from "@angular/router";
import {PermissionsFieldComponent} from "../../../shared/components/permissions-field/permissions-field.component";
import {SubscribingComponent} from "../../../shared/components/subscribing.component";

@Component({
  selector: 'cre-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.sass']
})
export class AddComponent extends SubscribingComponent {
  @ViewChild('permissionsField', {static: true}) permissionsField: PermissionsFieldComponent

  form: FormGroup
  nameControl: FormControl
  unknownError = false

  constructor(
    private formBuilder: FormBuilder,
    private groupService: GroupService,
    private router: Router
  ) {
    super()
  }

  ngOnInit(): void {
    this.nameControl = new FormControl(null, Validators.compose([Validators.required, Validators.minLength(3)]))
    this.form = this.formBuilder.group({
      name: this.nameControl
    })
  }

  submit() {
    if (this.form.valid && this.permissionsField.valid()) {
      this.subscribe(
        this.groupService.save(this.nameControl.value, this.permissionsField.allEnabledPermissions),
        {
          next: () => this.router.navigate(['/group/list']),
          error: err => {
            this.unknownError = true
            console.log(err)
          }
        }
      )
    }
  }
}
