import { Utility } from '../../core/utility';
import { EventManager, EventWrapper, EVENT_TYPE } from '../../lib/event-manager/event-manager';

const ENTER_IS_TAB_INITIALIZED_CLASS = 'enter-as-tab--initialized';
const AREA_SELECTOR = 'input, textarea';

@Utility({
    selector: '[uw-enter-as-tab]',
  })

export class EnterIsTab {
    _element;

    _eventManager;

    constructor(element) {

        if(!element) {
            throw new Error('EnterIsTab Utility cannot be setup without a field element');
        }

        this._element = element;

        this._eventManager = new EventManager();
        
        if (this._element.classList.contains(ENTER_IS_TAB_INITIALIZED_CLASS)) {
            return false;
        }

        this._element.classList.add(ENTER_IS_TAB_INITIALIZED_CLASS);
    }


    start() {
        let eventWrapper = new EventWrapper(EVENT_TYPE.KEYDOWN, this._captureEnter.bind(this), this._element);
        this._eventManager.registerNewListener(eventWrapper);
    }

    _captureEnter (e) {
        if(e.key === 'Enter') {
            e.preventDefault();
            let currentInputFieldId = this._element.id;
            let inputAreas = document.querySelectorAll(AREA_SELECTOR);
            let nextInputArea = null;
            for (let i = 0; i < inputAreas.length; i++) {
                if(inputAreas[i].id === currentInputFieldId) {
                    nextInputArea = inputAreas[i+1];
                    break;
                }
            }
            
            if(nextInputArea) {
                nextInputArea.focus();
            }
        }
    }

    destroy() {
        this._eventManager.cleanUp();
        if(this._element.classList.contains(ENTER_IS_TAB_INITIALIZED_CLASS))
            this._element.classList.remove(ENTER_IS_TAB_INITIALIZED_CLASS);
      }
}