import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { ToastService } from 'src/app/service/toast.service';
import { FormPageBase } from 'src/app/core/base/form-page-base';
import {
  UserSpace,
  UserSpaceCreateInput,
  UserSpaceUpdateInput,
} from 'src/app/model/entities/user-space';
import { UserSpacesDataService } from 'src/app/modules/admin/user-spaces/user-spaces.data.service';
import { catchError } from 'rxjs/operators';

@Component({
  selector: 'app-user-space-form-page',
  templateUrl: './user-space-form-page.component.html',
  styleUrl: './user-space-form-page.component.scss',
})
export class UserSpaceFormPageComponent extends FormPageBase<
  UserSpace,
  UserSpaceCreateInput,
  UserSpaceUpdateInput,
  UserSpacesDataService
> {
  constructor(private toast: ToastService) {
    super(undefined, '../..');
    if (!this.nodeId) {
      this.node = this.new();
      this.setForm(this.node);

      return;
    }

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

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

  buildForm() {
    this.form = new FormGroup({
      id: new FormControl<number | undefined>(undefined),
      name: new FormControl<string | undefined>(undefined, [
        Validators.required,
      ]),
      emailsToInvite: new FormControl<string[]>([]),
    });
    this.form.controls['id'].disable();
  }

  setForm(node?: UserSpace) {
    this.form.controls['id'].setValue(node?.id);
    this.form.controls['name'].setValue(node?.name);

    this.spinner.hide();
  }

  getCreateInput(): UserSpaceCreateInput {
    return {
      name: this.form.controls['name'].value ?? undefined,
      users: this.node.users?.map(x => x.id) ?? [],
    };
  }

  getUpdateInput(): UserSpaceUpdateInput {
    if (!this.node?.id) {
      throw new Error('Node id is missing');
    }

    return {
      id: this.form.controls['id'].value,
      name: this.form.controls['name'].pristine
        ? undefined
        : this.form.controls['name'].value,
      users: this.node.users?.map(x => x.id) ?? [],
    };
  }

  protected handleEMailInvitation(id: number): void {
    const emailsToInvite = this.form.controls['emailsToInvite'].value;
    if (!(emailsToInvite && emailsToInvite.length > 0)) {
      return;
    }

    this.dataService
      .inviteUsers(id, emailsToInvite)
      .pipe(
        catchError(err => {
          this.spinner.hide();
          this.toast.error('action.failed', 'user_space.invite_users');
          throw err;
        })
      )
      .subscribe(() => {
        this.spinner.hide();
        this.toast.success('user_space.invited_users');
      });
  }

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

  update(object: UserSpaceUpdateInput): void {
    this.handleEMailInvitation(object.id);
    this.dataService.update(object).subscribe(() => {
      this.spinner.hide();
      this.toast.success('action.created');
      this.close();
    });
  }
}
