import { Component, Input, OnInit, OnDestroy } from '@angular/core';
import { Editor } from 'ngx-editor';
import { Trait } from 'src/interfaces/interfaces';
import { ModalService } from 'src/services/modal/modal.service';

@Component({
  selector: 'trait-modal',
  templateUrl: './trait-modal.component.html',
  styleUrls: ['./trait-modal.component.scss'],
})
export class TraitModalComponent {
  @Input() public isUpdate: boolean = false;
  @Input() public trait: Trait | undefined;
  @Input() public isAddedFromCharacter: boolean = false;

  shortEditor: Editor = new Editor();
  longEditor: Editor = new Editor();
  html = '';
  toolbar: any = [
    // default value
    ['bold', 'italic'],
    ['bullet_list'],
    [{ heading: ['h3', 'h4', 'h5', 'h6'] }],
  ];

  public name: string = '';
  public shortDescription: string = '';
  public longDescription: string = '';
  public origin: string = '';

  public constructor(public modalAccessor: ModalService) {}

  ngOnInit(): void {
    if (this.isUpdate) {
      this.loadItem();
    }
  }

  ngOnDestroy(): void {
    this.shortEditor.destroy();
    this.longEditor.destroy();
  }

  // FUNCTIONS

  public loadItem(): void {
    this.name = this.trait!.name;
    this.shortDescription = this.trait!.shortDescription;
    this.longDescription = this.trait!.longDescription;
    this.origin = this.trait!.origin;
  }

  public createTrait(): Trait {
    return {
      name: this.name,
      shortDescription: this.shortDescription,
      longDescription: this.longDescription,
      origin: this.origin,
    };
  }

  // RESPONSES

  public cancel(): void {
    this.modalAccessor.handleModalClosing('cancel', undefined);
  }

  public add(): void {
    this.modalAccessor.handleModalClosing('add', this.createTrait());
  }

  public update(): void {
    this.modalAccessor.handleModalClosing('update', this.createTrait());
  }
}
