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

@Component({
  selector: 'ability-modal',
  templateUrl: './ability-modal.component.html',
  styleUrls: ['./ability-modal.component.scss'],
})
export class AbilityModalComponent {
  @Input() public isUpdate: boolean = false;
  @Input() public ability: Ability | 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 charges: number = 0;
  public currentlyUsedCharges: number = 0;
  public cost: string = 'none';
  public shortDescription: string = '';
  public longDescription: string = '';
  public costs: string[] = ['none', 'action', 'bonus', 'reaction'];
  public chargesArray: number[] = Array.from({ length: 101 }, (_, i) => i);

  public constructor(private modalAccessor: ModalService) {}

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

  // make sure to destory the editor
  ngOnDestroy(): void {
    this.shortEditor.destroy();
    this.longEditor.destroy();
  }

  //   FUNCTIONS

  public loadItem(): void {
    this.name = this.ability!.name;
    this.charges = this.ability!.charges;
    this.currentlyUsedCharges = this.ability!.currentlyUsedCharges;
    this.cost = this.ability!.cost;
    this.shortDescription = this.ability!.shortDescription;
    this.longDescription = this.ability!.longDescription;
  }

  public createAbility(): Ability {
    return {
      name: this.name,
      shortDescription: this.shortDescription,
      longDescription: this.longDescription,
      cost: this.cost,
      charges: parseInt(this.charges.toString()),
      currentlyUsedCharges: Math.min(this.currentlyUsedCharges, this.charges),
    };
  }

  // RESPONSES

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

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

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