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

@Component({
  selector: 'app-simple-item-modal',
  templateUrl: './simple-item-modal.component.html',
  styleUrl: './simple-item-modal.component.scss',
})
export class SimpleItemModalComponent {
  public constructor(private modalAccessor: ModalService) {}
  @Input() public item: any;
  @Input() public isUpdate: boolean = false;
  @Input() public isFood: boolean = false;

  editor: Editor = new Editor();
  html = '';
  toolbar: any = [
    // default value
    ['bold', 'italic'],
    ['bullet_list'],
    [{ heading: ['h3', 'h4', 'h5', 'h6'] }],
  ];
  public name: string = '';
  public description: string = '';
  public quantity: number = 0;
  public weight: number = 0;
  public value: number = 0;
  public isReady: boolean = false;

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

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

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

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

  private loadItem(): void {
    this.name = this.item.name;
    this.description = this.item.description;
    this.quantity = this.item.quantity;
    this.weight = this.item.weight;
    this.value = this.item.value;
    this.isReady = this.item.isReady;
  }

  private createItem(): any {
    if (this.isFood) {
      return {
        name: this.name,
        isReady: this.isReady,
        description: this.description,
        quantity: this.quantity,
        weight: this.weight,
      };
    } else {
      return {
        name: this.name,
        description: this.description,
        quantity: this.quantity,
        weight: this.weight,
        value: this.value,
      };
    }
  }

  private resetItem(): void {
    this.name = '';
    this.description = '';
    this.quantity = 0;
    this.weight = 0;
    this.value = 0;
    this.isReady = false;
  }
}
