import eventTpl from "./tpls/event.tpl";
import _ from 'underscore';

const SUPPORTED_EVENTS = [{ type: "click", label: "点击" }];

const createEventDOM = (components) => {
  return $(`
    <li>
      <span>当</span>
      <select class="event-selector">
        ${SUPPORTED_EVENTS.map(({ type, label }) => `<option value=${type}>${label}</option>`)}
      </select>
      <span>时，触发</span>
      <select class="component-selector">
        ${components.map((comp) => `<option value=${comp.ccid}>${comp.ccid}</option>`)}
      </select>
      <select class="animation-selector"></select>
      <i class="spicon icon-delete js-delete"></i>
    </li>
  `);
};

export default function (editor) {
  editor.TraitManager.addType("basic-traits-event", {
    noLabel: true,

    addEvent(component, $el, $eventList) {
      const $eventEntry = createEventDOM(editor.getComponents());

      const $eventSelector = $eventEntry.find('.event-selector');
      const $compSelector = $eventEntry.find('.component-selector');
      const $animationSelector = $eventEntry.find('.animation-selector');

      // 每一个select选中时，更新全局的eventlist
      $eventSelector.on('change', () => {
        this.getEvents({ elInput: $el, component });
      });
      $compSelector.on('change', () => {
        this.getEvents({ elInput: $el, component });
      });
      $animationSelector.on('change', () => {
        this.getEvents({ elInput: $el, component });
      });
      $eventList.append($eventEntry);
    },

    getEvents({ elInput, component }) {
      const events = [];

      elInput.querySelectorAll('li').forEach(li => {
        events.push({
          source: component.ccid,
          target: $(li).find('.component-selector').val(),
          action: $(li).find('.event-selector').val(),
          result: $(li).find('.animation-selector').val()
        });
      });

      component.addAttributes({ 'data-events': JSON.stringify(events) });
      component.trigger('change:events', [component.ccid, events]);
    },

    // Return a simple HTML string or an HTML element
    createInput({ component, trait }) {
      const $traitEl = $(eventTpl);
      const $eventList = $traitEl.find(".event-list");
      const $el = document.createElement('div');

      if (!_.isEmpty(editor.EventManager.events) && !_.isEmpty(editor.EventManager.events[component.ccid])) {
        editor.EventManager.events[component.ccid].forEach((event) => {
          const $eventEntry = createEventDOM(editor.getComponents());
          $eventEntry.find('.component-selector').val(event.target);
          $eventEntry.find('.event-selector').val(event.action);
          $eventEntry.find('.animation-selector').val(event.result);

          $eventList.append($eventEntry);
        });
      }

      $traitEl.on("click", '.js-create', this.addEvent.bind(this, component, $el, $eventList));

      $traitEl.on('click', '.js-delete', (ev) => {
        const $target = $(ev.target);

        $target.parent('li').remove();

        this.getEvents({ elInput: $el, component });
      })

      $el.appendChild($traitEl[0]);

      return $el;
    },

    // Update the component based element changes
    onEvent({ elInput, component }) {
      this.getEvents({ elInput, component });
    },

    onUpdate({ elInput, component }) {
      const componentOptions = (selected) => {
        return editor.getComponents().map(comp => `<option value=${comp.ccid} ${comp.ccid === selected ? 'selected' : ''}>${comp.ccid}</option>`)
      }

      $(elInput)
        .find('.component-selector')
        .each((index, selector) => {
          $(selector).html(componentOptions(selector.value))
        })
    },
  });
}
