import MutableArray from '@ember/array/mutable';
import { action } from '@ember/object';
import Component from '@glimmer/component';

export interface UtilMapEditSignature {
  // The arguments accepted by the component
  Args: {
    list: MutableArray<{ key: string; value: string }>;
    prefix: string;
    onNewElement: (index: number) => void;
    onDeleteElement: (index: number) => void;
  };
  // Any blocks yielded by the component
  Blocks: {
    default: [];
  };
  // The element to which `...attributes` is applied in the component template
  Element: null;
}

export default class UtilMapEdit extends Component<UtilMapEditSignature> {
  @action addElement() {
    MutableArray.apply(this.args.list);
    this.args.list.pushObject({ key: '', value: '' });
    if (this.args.onNewElement)
      this.args.onNewElement(this.args.list.length - 1);
  }

  @action removeElement(index: number) {
    MutableArray.apply(this.args.list);
    //let index = this.args.list.find((elem) => elem == content)
    //let index = this.listCopy.findIndex((d) => d == content)
    this.args.list.removeAt(index);
    if (this.args.onDeleteElement) this.args.onDeleteElement(index);
  }
}
