import { Component, OnInit, Optional } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { UntypedFormBuilder, UntypedFormControl, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { ClientsApiService } from '@fleio-api/client-user/client/clients-api.service';
import { PanelLayoutComponent } from '@shared/layout/panel-layout/panel-layout.component';
import { map } from 'rxjs/operators';
import { Observable, of } from 'rxjs';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import { IRoleModel } from '@fleio-api/client-user/roles/model/role.model';
import { RolesApiService } from '@fleio-api/client-user/roles/roles-api.service';

@Component({
  selector: 'app-role-edit-form',
  templateUrl: './role-edit-form.component.html',
  styleUrls: ['./role-edit-form.component.scss']
})
export class RoleEditFormComponent extends DetailsFormBase<IRoleModel> implements OnInit {
  country: UntypedFormControl = new UntypedFormControl('', Validators.required);

  requireOwner = this.config.authService.feature('ui.clients&users.roles.require-owner');
  ownerValidators = this.requireOwner ? [Validators.required] : [];

  roleForm = this.formBuilder.group({
    name: ['', Validators.required],
    owner: [
      '',
      [this.validObjectSelectedValidator(), ...this.ownerValidators]
    ],
    public: [false],
    parent: ['', this.validObjectSelectedValidator()],
  });

  ownerPlaceholderUnselected = $localize`Select owner ...`;
  ownerPlaceholderSelected = $localize`Owner`;
  rolePlaceholderUnselected = $localize`Select parent ...`;
  rolePlaceholderSelected = $localize`Parent`;

  rolesSwitchMap: (search: string) => Observable<any>;

  constructor(
    private formBuilder: UntypedFormBuilder, public rolesApiService: RolesApiService, private router: Router,
    private config: ConfigService, private clientsApiService: ClientsApiService,
    @Optional() public panelLayout?: PanelLayoutComponent,
  ) {
    super();
  }

  ngOnInit() {
    if (this.objectController) {
      this.objectController.actionCallback = () => this.saveRole();
    }

    this.rolesSwitchMap = (search) => this.rolesApiService.getPossibleParents(
        this.object?.id ? {search, current_role: this.object.id} : {search},
      ).pipe(map(roles => roles.objects));

    if (this.object) {
      this.roleForm.patchValue(this.object);
      if (this.object.owner) {
        this.clientsApiService.get(this.object.owner).subscribe(value => {
          this.roleForm.controls.owner.setValue(value);
        });
      }
      if (this.object.parent) {
        this.rolesApiService.get(this.object.parent).subscribe(value => {
          this.roleForm.controls.parent.setValue(value);
        });
      }
    }
  }

  private saveRole(): Observable<IActionResult> {
    const value = this.roleForm.value;
    if (value.owner?.id) {
      value.owner = value.owner.id;
    }
    if (value.parent?.id) {
      value.parent = value.parent.id;
    }

    this.createOrUpdate(
      this.rolesApiService,
      value,
    ).subscribe(() => {
      this.router.navigateByUrl(
        this.config.getPrevUrl('clients-users/roles')
      ).catch(() => {
      });
    });

    return of(null);
  }
}
