import { Utility } from '../../core/utility';

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;

    constructor(element) {

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

        this._element = element;
        
        if (this._element.classList.contains(ENTER_IS_TAB_INITIALIZED_CLASS)) {
            return false;
        }

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


    start() {
        this._element.addEventListener('keydown', (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() {
        console.log('TBD: Destroy EnterIsTab');
      }
}