import { ICellRendererParams } from "ag-grid-community";
import { KebabCase } from "../../utils/kebab-case";
import { ButtonsColDefAction } from "../../vm/list-view-buttons-coldef";
import BaseRenderer from "./base-renderer";

export default class ButtonRenderer extends BaseRenderer {

  protected buttons: ButtonsColDefAction<any>[];

  public init(params: ICellRendererParams & { buttons: ButtonsColDefAction<any>[] }) {
    this.buttons = params.buttons;
    super.init(params);
    super.setupGui();
  }

  public setupContentGui(): string {
    this.eGui.style.display = 'flex';
    this.eGui.style.alignItems = 'center';
    this.eGui.style.justifyContent = 'flex-start';

    return this.buttonsToShow
      .reduce((html: string, button: ButtonsColDefAction<any>, index: number) => {
        let bindings = ButtonsColDefAction.uiBtnProps.reduce((html, prop) => {
          let btnHtml = '';
          let value = this.getValueOfConfig(button[prop], this.params.data);
          if (null !== value) {
            btnHtml = ` ${KebabCase.fromCamelCase(prop)}${typeof value == 'boolean' ? '.one-time' : ''}="${value}"`;
          }
          return html + btnHtml
        }, '');

        if (this.params?.data?.__busy && this.params?.data?.__busy[index]) {
          bindings += ' busy.one-time="true"';
        }

        let svgSlot = '';
        let icon = this.getValueOfConfig(button.icon, this.params.data);
        if (typeof icon == 'string') {
          if (/.svg$/.test(icon)) {
            svgSlot = `<span slot="svg-icon" class="ui-btn__icon"><div class="ui-icon"><img src="${icon}"/></div></span>`;
          } else {
            bindings += ` icon="${icon}"`;
          }
        }

        return html + `<ui-button click.delegate="btnClicked(${index})" ${bindings}><div class="ui-btn__label">${svgSlot}</div></ui-button>`;
      }, '');
  }

  public async btnClicked(index: number) {
    var button = this.buttonsToShow[index];
    if (button !== null && button.clicked !== null) {
      this.params.data.__busy = this.params.data.__busy || {};
      this.params.data.__busy[index] = true;
      this.params.api.redrawRows({ rowNodes: [this.params.node] });

      if (button.viewModel != null) {
        await button.clicked.apply(button.viewModel, this.params.data);
      }
      else {
        await button.clicked(this.params.data)
      }

      this.params.data.__busy[index] = false;
      this.params.api.redrawRows({ rowNodes: [this.params.node] });
    }
  }

  private get buttonsToShow(): ButtonsColDefAction<any>[] {
    return this.buttons.filter(button => !this.getValueOfConfig(button.hidden, this.params.data));
  }

  private getValueOfConfig(propValue: (string | ((data: any) => string)) | (boolean | ((data: any) => boolean)), data: any): string | boolean {
    if (propValue == null) {
      return null;
    }
    if (isFunction(propValue)) {
      return data !== null ? propValue(data) : null;
    } else {
      return propValue;
    }
  }
}