import { Container, createOverrideContext, ViewCompiler, ViewResources, ViewSlot } from 'aurelia-framework';
import 'select2';
import { UIInternal } from '../../../utils/ui-internal';

var AllowClear = jQuery.fn.select2.amd.require('select2/selection/allowClear');
var Utils = jQuery.fn.select2.amd.require('select2/utils');
var KEYS = jQuery.fn.select2.amd.require('select2/keys');

export class CustomAllowClear extends AllowClear {

  bind(decorated, container, $container) {
    decorated.call(this, container, $container);
    var self = this;
    if (this.placeholder == null) {
      if (this.options.get('debug') && window.console && console.error) {
        console.error(
          'Select2: The `allowClear` option should be used in combination ' +
          'with the `placeholder` option.'
        );
      }
    }

    this.$selection.on('mousedown', '.select2-selection__clear',
      (evt) => {

        if (this.isDisabled()) {
          return;
        }

        let $clear = this.$selection.find('.select2-selection__clear');

        // Ignore the event if nothing has been selected
        if ($clear.length === 0) {
          return;
        }

        evt.stopPropagation();
        this.$selection.find('.select2-selection__clear').remove();

        let data = Utils.GetData($clear[0], 'data');

        let previousVal = this.$element.val();
        this.$element.val(this.placeholder?.id);

        let unselectData = {
          data: data
        };
        this.trigger('clear', unselectData);
        if ((unselectData as any).prevented) {
          this.$element.val(previousVal);
          return;
        }

        for (let d = 0; d < data.length; d++) {
          unselectData = {
            data: data[d]
          };

          // Trigger the `unselect` event, so people can prevent it from being
          // cleared.
          this.trigger('unselect', unselectData);

          // If the event was prevented, don't clear it out.
          if ((unselectData as any).prevented) {
            this.$element.val(previousVal);
            return;
          }
        }
      })

    container.on('keypress', (evt) => {
      if (container.isOpen()) {
        return;
      }

      if (evt.which == KEYS.DELETE || evt.which == KEYS.BACKSPACE) {

        if (self.isDisabled()) {
          return;
        }

        let $clear = this.$selection.find('.select2-selection__clear');

        // Ignore the event if nothing has been selected
        if ($clear.length === 0) {
          return;
        }

        evt.stopPropagation();
        this.$selection.find('.select2-selection__clear').remove();
        let data = Utils.GetData($clear[0], 'data');

        let previousVal = this.$element.val();
        this.$element.val(self.placeholder?.id);

        let unselectData = {
          data: data
        };
        this.trigger('clear', unselectData);
        if ((unselectData as any).prevented) {
          this.$element.val(previousVal);
          return;
        }

        for (let d = 0; d < data.length; d++) {
          unselectData = {
            data: data[d]
          };

          // Trigger the `unselect` event, so people can prevent it from being
          // cleared.
          this.trigger('unselect', unselectData);

          // If the event was prevented, don't clear it out.
          if ((unselectData as any).prevented) {
            this.$element.val(previousVal);
            return;
          }
        }
      }
    });
  }

  update(decorated, data) {
    decorated.call(this, data);

    this.$selection.find('.select2-selection__clear').remove();
    this.$selection[0].classList.remove('select2-selection--clearable');

    if (this.$selection.find('.select2-selection__placeholder').length > 0 ||
      data.length === 0) {
      return;
    }

    let selectionId = this.$selection.find('.select2-selection__rendered')
      .attr('id');

    let removeAll = this.options.get('translations').get('removeAllItems');

    // let html = `<template><ui-icon class="select2-selection__clear" icon="digi-cross"></ui-icon></template>`;
    let html = `<template><ui-button icon="digi-cross" class="select2-selection__clear" type="tool"></ui-button></template>`;
    let view = UIInternal.compileTemplate(html, this, createOverrideContext(this));

    let $remove = $(view.fragment.children[0]);

    $remove.attr('title', removeAll());
    $remove.attr('aria-label', removeAll());
    $remove.attr('aria-describedby', selectionId);
    Utils.StoreData($remove[0], 'data', data);

    this.$selection.prepend($remove);
    this.$selection[0].classList.add('select2-selection--clearable');
  };
}
