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 {
  Domain,
  DomainCreateInput,
  DomainUpdateInput,
} from 'src/app/model/entities/domain';
import { DomainsDataService } from 'src/app/modules/admin/administration/domains/domains.data.service';

@Component({
  selector: 'app-domain-form-page',
  templateUrl: './domain-form-page.component.html',
  styleUrl: './domain-form-page.component.scss',
})
export class DomainFormPageComponent extends FormPageBase<
  Domain,
  DomainCreateInput,
  DomainUpdateInput,
  DomainsDataService
> {
  constructor(private toast: ToastService) {
    super();
    if (!this.nodeId) {
      this.node = this.new();
      this.setForm(this.node);

      return;
    }

    this.dataService
      .load([{ id: { equal: this.nodeId } }])
      .subscribe(apiKey => {
        this.node = apiKey.nodes[0];
        this.setForm(this.node);
      });
  }

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

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

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

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

  getUpdateInput(): DomainUpdateInput {
    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 ?? undefined),
    };
  }

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

  update(apiKey: DomainUpdateInput): void {
    this.dataService.update(apiKey).subscribe(() => {
      this.spinner.hide();
      this.toast.success('action.created');
      this.close();
    });
  }
}
