import { Component } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { ToastService } from 'src/app/service/toast.service';
import { FormPageBase } from 'src/app/core/base/form-page-base';
import {
  NotExistingUser,
  User,
  UserCreateInput,
  UserUpdateInput,
} from 'src/app/model/auth/user';
import { Role } from 'src/app/model/entities/role';
import { UsersDataService } from 'src/app/modules/admin/administration/users/users.data.service';

@Component({
  selector: 'app-user-form-page',
  templateUrl: './user-form-page.component.html',
  styleUrl: './user-form-page.component.scss',
})
export class UserFormPageComponent extends FormPageBase<
  User,
  UserCreateInput,
  UserUpdateInput,
  UsersDataService
> {
  notExistingUsers: NotExistingUser[] = [];
  roles: Role[] = [];

  constructor(private toast: ToastService) {
    super();
    this.dataService.getAllRoles().subscribe(roles => {
      this.roles = roles;
    });

    if (!this.nodeId) {
      this.dataService.getNotExistingUsersFromKeycloak().subscribe(users => {
        this.notExistingUsers = users ?? [];
        this.node = this.new();
        this.setForm(this.node);
      });

      return;
    }

    this.dataService.loadById(this.nodeId).subscribe(user => {
      this.node = user;
      this.setForm(this.node);
    });
  }

  new(): User {
    return {} as User;
  }

  buildForm() {
    this.form = new FormGroup({
      id: new FormControl<number | undefined>(undefined),
      keycloakId: new FormControl<string | undefined>(undefined),
      username: new FormControl<string | undefined>(undefined),
      email: new FormControl<string | undefined>(undefined),
      roles: new FormControl<Role[]>([]),
    });
    this.form.controls['id'].disable();
    this.form.controls['username'].disable();
    this.form.controls['email'].disable();
  }

  setForm(node?: User) {
    this.form.controls['id'].setValue(node?.id);
    this.form.controls['username'].setValue(node?.username);
    this.form.controls['email'].setValue(node?.email);
    this.form.controls['roles'].setValue(node?.roles ?? []);

    if (this.notExistingUsers.length > 0) {
      this.form.controls['id'].enable();
      this.form.controls['keycloakId'].reset(undefined, { required: true });
    }
  }

  getCreateInput(): UserCreateInput {
    return {
      keycloakId: this.form.controls['keycloakId'].pristine
        ? undefined
        : this.form.controls['keycloakId'].value,
      roles: this.form.controls['roles'].pristine
        ? undefined
        : this.form.controls['roles'].value,
    };
  }

  getUpdateInput(): UserUpdateInput {
    return {
      id: this.form.controls['id'].value,
      roles: this.form.controls['roles'].pristine
        ? undefined
        : this.form.controls['roles'].value,
    };
  }

  create(user: UserCreateInput): void {
    this.dataService.create(user).subscribe(() => {
      this.spinner.hide();
      this.toast.success('action.created');
      this.close();
    });
  }

  update(user: UserUpdateInput): void {
    this.dataService.update(user).subscribe(() => {
      this.spinner.hide();
      this.toast.success('action.updated');
      this.close();
    });
  }
}
