<script>
import { Vue, Component, Prop, Watch, PropSync } from 'vue-property-decorator';
import itfButton from '../button/Button';
import itfDropdownMenu from './DropdownMenu';

let globalModalIndex = 0; // base modal z-index

export default @Component({
  functional: true,
  name: 'itfDropdown',
  components: {
    itfButton,
    itfDropdownMenu
  },
})
class itfDropdown extends Vue {
  @PropSync('visible') value;
  @Prop({ type: String, default: 'down', validator: (value) => ['down', 'start', 'end', 'up'].includes(value) }) placement;
  @Prop({ type: String, default: 'click', validator: (value) => ['click', 'focus', 'hover', 'manual'].includes(value) }) trigger;
  @Prop({ type: String, default: 'Dropdown' }) label;
  @Prop({ type: Boolean }) right;
  @Prop({ type: Boolean }) toggle;
  @Prop({ type: Boolean }) shadow;
  @Prop({ type: Boolean }) disabled;
  @Prop({ type: Boolean }) text;
  @Prop({ type: Boolean }) appendToBody;
  @Prop({ type: Boolean }) appendToContext;
  @Prop({ validator: (value) => [true, false, 'inside', 'outside'].includes(value), default: true }) autoclose;
  @Prop({ type: Object, default: () => ({}) }) buttonOptions;
  @Prop({ type: Object, default: () => ({}) }) menuOptions;

  modalId = '';

  render (createElement, context) {
    const { props, slots, data, listeners } = context;
    const modalId = `dropdownId${globalModalIndex++}`;
    const { buttonOptions, toggle, text, disabled, label, appendToBody } = props;
    const { button, default: defaultSlot } = slots();
    let elements = [
      createElement(
        text ? 'div' : itfButton,
        {
          staticClass: data.staticClass || '',
          props: buttonOptions || {},
          class: { 'dropdown-toggle': toggle },
          attrs: { id: modalId, 'data-bs-toggle': 'dropdown', 'aria-expanded': 'false', ...(data.attrs || {}) },
        },
        button || label
      ),
      disabled ? null : createElement(
        itfDropdownMenu,
        {
          ref: data.ref,
          props: { ...props, toggleId: modalId },
          on: {
            open: () => {
              if (listeners.open) {
                listeners.open();
              }
            },
            close: () => {
              if (listeners.close) {
                listeners.close();
              }
            }
          }
        },
        defaultSlot
      )
    ];
    if (!appendToBody) {
      elements = [createElement('div', { class: `dropdown ${data.staticClass || ''}` }, elements)];
    }
    return elements;
  }

  show() {
    if (this.modalEl) {
      this.modalEl.show();
    }
  }

  hide() {
    if (this.modalEl) {
      this.modalEl.hide();
    }
  }
}
</script>
