import { getCookie, setCookie } from '../../global/helpers/athena-global-helper.js';
import { athenaFetchApi } from '../../global/athena-fetch-api.js';
import { athenaConfigOptions } from '../../global/athena-config.js';

export function searchSuggestions() {

    athenaFetchApi({
        'service': 'search-suggestions'
    })
        .then(response => {
            //Destruction of Object
            const {
                enabled_disabled: enabledDisabled,
                placeholder_text: placeholderText,
                rotation_in_seconds: rotationSeconds,
                keep_keyword: keepKeyword,
                delay_at_start: delayAtStart
            } = response;

            const suggestionData = response;
            //Save Suggestion Keywords for later use
            athenaConfigOptions.suggestedKeywords = suggestionData.suggestions_keywords;

            const rotateElements = [];

            var delayAtStartSeconds = parseInt(delayAtStart);
            if(isNaN(delayAtStartSeconds)) {
                delayAtStartSeconds = 0;
            }

            // Current sentence being processed
            var _PART = 0;

            // Character number of the current sentence being processed
            var _PART_INDEX = 0;

            // Holds the handle returned from setInterval
            var _INTERVAL_VAL;

            // Element that holds the text
            var _ELEMENT = document.querySelector('#search');

            //delete cookie to prevent showing keyword on other page / refreshed
            eraseCookie('key pressed');

            if(enabledDisabled === 'on') {

                if (placeholderText === '' || placeholderText === 'off') {
                    placeholderText.value = 'Search for...';
                }

                /**
                 * Parsing To INT
                 * @type {number}
                 */
                var rotateSeconds = parseInt(rotationSeconds);
                var keepKeywordSeconds = parseInt(keepKeyword);

                /**
                 * Checking if keepKeyword is Not a Number
                 */
                if(isNaN(keepKeywordSeconds)) {
                    keepKeywordSeconds = 1;
                }

                _ELEMENT.setAttribute('placeholder', `${placeholderText} `);

                if(suggestionData.suggestions_keywords.length > 0) {

                    suggestionData.suggestions_keywords.forEach(suggestionKeyword => {
                        rotateElements.push(suggestionKeyword.content);
                    });

                    var _CONTENT = rotateElements;

                    setTimeout(() => {
                        _INTERVAL_VAL = setInterval(() => {
                            Type();
                        }, 70);
                    }, delayAtStartSeconds * 1000);
                }
            } else {
                _ELEMENT.setAttribute('placeholder', `${placeholderText} `);
            }

            function Type() {
                //halt animation if there window/tab is out of focus
                if(document.hasFocus()) {

                    let text = _CONTENT[_PART].substring(0, _PART_INDEX + 1);
                    _ELEMENT.setAttribute('placeholder', placeholderText + ' ' + text);
                    _PART_INDEX++;

                    // If full sentence has been displayed then start to delete the sentence after some time
                    if (text === _CONTENT[_PART]) {

                        //here check cookie and put word in input
                        let cookieRetrievedValue = getCookie('key pressed');

                        if (cookieRetrievedValue === '1') {
                            //stop effect
                            clearInterval(1);
                            //write word
                            _ELEMENT.value = _CONTENT[_PART];
                            //delete cookie
                            eraseCookie('key pressed');
                        }

                        clearInterval(_INTERVAL_VAL);
                        setTimeout(() => {
                            _INTERVAL_VAL = setInterval(Delete, 50);
                        }, keepKeywordSeconds * 1000);
                    }
                } else {
                    clearInterval(1);
                }
            }

            /**
             * Delete Keywords
             */
            function Delete() {

                let text =  _CONTENT[_PART].substring(0, _PART_INDEX - 1);
                _ELEMENT.setAttribute('placeholder', placeholderText + ' ' + text);
                _PART_INDEX--;

                // If sentence has been deleted then start to display the next sentence
                if(text === '') {
                    //clear cookie
                    eraseCookie('key pressed');

                    clearInterval(_INTERVAL_VAL);

                    // If last sentence then display the first one, else move to the next
                    _PART === _CONTENT.length - 1 ? _PART = 0 : _PART++;
                    _PART_INDEX = 0;

                    // Start to display the next sentence after some time
                    setTimeout(() =>  {
                        _CONTENT = shuffleArray(_CONTENT);
                        _INTERVAL_VAL = setInterval(Type, 70);
                    }, rotateSeconds * 1000);
                }
            }

            /**
             * Execute Entering Search trigger
             */
            document.addEventListener('keydown', (event) => {
                if (_ELEMENT.value === '') {
                    if (event.code === 39 || event.code === 32 || event.code === 13) {
                        if(event.code === 13) {
                            event.preventDefault();
                        }

                        executeEnteringSearch();
                    }
                }
            });

            /**
             * Execute Entering Search Function
             */
            function executeEnteringSearch() {
                //check if input is empty
                const currentPlaceholder = _ELEMENT.getAttribute('placeholder').trim();
                const defaultPlaceholder = placeholderText.trim();
                const sumPlaceholder = placeholderText + ' ' + _CONTENT[_PART];

                eraseCookie('key pressed');

                if (currentPlaceholder === sumPlaceholder) {
                    _ELEMENT.value = _CONTENT[_PART];
                    //delete cookie
                    eraseCookie('key pressed');
                }

                if (currentPlaceholder !== defaultPlaceholder) {
                    setCookie('key pressed', '1', '1');
                } else {
                    //delete cookie
                    eraseCookie('key pressed');
                }
            }
        });
}

/**
 * Shuffle Array Function
 *
 * @param array
 * @returns {*}
 */
function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        let j = Math.floor(Math.random() * (i + 1));
        let temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

    return array;
}

/**
 * Erase Cookie Function
 *
 * @param name
 */
function eraseCookie(name) {
    document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}