import { athenaConfig, athenaConfigOptions } from '../athena-config.js';
import { athenaFetchApi } from '../athena-fetch-api.js';
import { userToken } from '../helpers/athena-global-helper.js';
import { openLandingPageSidebar } from '../../demo/open-landing-page-sidebar.js'


/**
 * Search History Function
 *
 * @param productId
 * @returns {number}
 */
function searchHistory(productId) {
    const date = Date.now() + 86400;
    let searchHistory = localStorage.getItem('athenaSearchHistory');

    if(searchHistory) {
        searchHistory = JSON.parse(searchHistory);

        if (searchHistory[productId] && searchHistory[productId]['token'] === athenaConfig.websiteToken) {
            searchHistory[productId]['token'] = athenaConfig.websiteToken;
            searchHistory[productId]['expiration'] = date;
            searchHistory[productId]['oid'] = productId;
            localStorage.setItem('athenaSearchHistory', JSON.stringify(searchHistory));
        } else {
            searchHistory[productId] = {};
            searchHistory[productId]['token'] = athenaConfig.websiteToken;
            searchHistory[productId]['expiration'] = date;
            searchHistory[productId]['oid'] = productId;
            localStorage.setItem('athenaSearchHistory', JSON.stringify(searchHistory));
        }
    } else {
        const searchHistory = {};
        searchHistory[productId] = {};
        searchHistory[productId]['token'] = athenaConfig.websiteToken;
        searchHistory[productId]['expiration'] = date;
        searchHistory[productId]['oid'] = productId;
        localStorage.setItem('athenaSearchHistory', JSON.stringify(searchHistory));
    }

    return date;
}

/**
 * Get Query from Url
 *
 * @returns {boolean|string}
 */
function getQueryFromUrl() {
    let sPageURL = window.location.search.substring(1),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === 'q') {
            return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
        }
    }
}

/**
 * Check if value type is autocomplete
 *
 * @return {boolean}
 */
function isAutocomplete() {
    return !!document.querySelector('#search')?.value;
}

/**
 * Get Search Keywords Function
 *
 * @param isLandingPage
 * @param productId
 * @return {*}
 */
function getSearchKeywords(
    isLandingPage,
    productId
) {
    const actions = {
        landingPage: () => getQueryFromUrl() + ',',
        autocomplete: () => document.querySelector(`[data-element-id-autocomplete="${productId}"]`)?.dataset.termsAutocomplete || '',
        firstClick: () => 'First Click'
    };

    const actionKey =
        isLandingPage ? 'landingPage' :
            isAutocomplete() ?
                'autocomplete' :
                'firstClick';

    return actions[actionKey]();
}

/**
 * Product Click Function
 *
 * @param event
 * @param type
 * @param isLandingPage
 */
export function productClick(event, type, isLandingPage = null) {

    const productId = event.dataset[`elementId${type.charAt(0).toUpperCase() + type.slice(1)}`];

    if(typeof productId !== 'undefined') {
        userToken();
        searchHistory(productId);

        // Get current attribution (source & channel)
        const attribution = typeof window.athenaGetCurrentAttribution === 'function'
            ? window.athenaGetCurrentAttribution()
            : { source: '', channel: '' };

        athenaFetchApi({
            'service': 'product-click',
            'athenaUid': athenaConfigOptions.athenaUid,
            'productId': productId,
            'type': type,
            'searchKeywords': getSearchKeywords(isLandingPage, productId),
            'source': attribution.source || '',
            'channel': attribution.channel || ''
        }, null, true)
            .then(response => console.info('Athena Product Clicked!'));

        if(athenaConfig.isDemo){
            athenaFetchApi({
                'service': 'getProductById',
                'id' : productId
            })
                .then(response => {
                    const data = response.data;

                    const attributes = [];
                    data.attributes.forEach((attribute) => {
                        attributes.push([attribute.name, attribute.label]);
                    });

                    openLandingPageSidebar(data, attributes);
                });
        }
    }
}

