import type { App, DirectiveBinding, Plugin } from 'vue';
import FieldComponent from './FieldComponent.vue';

function onFocus(binding: DirectiveBinding<any>, focusState: boolean) {
  if (!binding?.value?.focus) {
    return;
  }

  binding.value.focus(focusState);
}

export const field: Plugin = {
  install: (app: App) => {
    app.directive('field', {
      mounted(el, binding) {
        el.addEventListener('focus', () => {
          onFocus(binding, true);
        });
        el.addEventListener('blur', () => {
          onFocus(binding, false);
        });
      },
      unmounted(el) {
        el.removeEventListener('focus', () => {});
        el.removeEventListener('blur', () => {});
      },
    });

    app.component('field', FieldComponent);
    app.component('Field', FieldComponent);
  },
};
