import Vue from 'vue';
import Main from './main.vue';

const PopupBox = Vue.extend(Main);
let instance;
const Symbolbox = function(baseUrl) {
  instance = new PopupBox().$mount();
  instance.setBaseUrl(baseUrl);
  document.body.appendChild(instance.$el);
};
const handlerFn = function(e) {
  let $dom = e.target;
  let isOpen = false;
  if (
    $dom.tagName.toLowerCase() === 'input' &&
    ($dom.getAttribute('type') === 'input' ||
      $dom.getAttribute('type') === 'text')
  ) {
    isOpen = true;
  }
  if ($dom.tagName.toLowerCase() === 'textarea') {
    isOpen = true;
  }
  if ($dom.getAttribute('readonly') === 'readonly') {
    isOpen = false;
  }
  if ($dom.disabled) {
    isOpen = false;
  }
  if (isOpen && $dom.closest('#symbolbox') === null) {
    instance.hide(false);
    if (instance.inputEl !== $dom) {
      instance.setOrignalDom($dom);
    }
  } else if ($dom.closest('#symbolbox') === null) {
    instance.hide(true);
  } else if ($dom.tagName.toLowerCase() !== 'input' && $dom.closest('#symbolbox')) {
    instance.inputEl.focus();
  }
};
/*
const keydownFn = function(e) {
  let $dom = e.target;
  if (
    $dom.tagName.toLowerCase() === 'input' ||
    $dom.tagName.toLowerCase() === 'textarea'
  ) {
    instance.hide(true);
  }
};*/
Symbolbox.open = function() {
  document.addEventListener('mousedown', handlerFn);
  /* document.addEventListener('keydown', keydownFn);*/
};
Symbolbox.close = function() {
  instance && instance.hide(true);
  document.removeEventListener('mousedown', handlerFn);
};
Symbolbox.destroy = function() {
  instance && instance.$destroy();
};
Symbolbox.options = function(opts) {
  instance && instance.options(opts);
};

export default Symbolbox;
