import {athenaConfig, athenaConfigOptions} from '../../../global/athena-config.js';
import { athenaFetchApi } from '../../../global/athena-fetch-api.js';
import { appendSearchProducts } from '../../renderer/products.js';
import { addObserverToProducts } from '../../helper/infinite-scroll/add-observer-to-products.js';
import { appendProductEnd } from '../../renderer/product-end.js';
import { getUrlSearchParams } from '../../helper/url-search-params.js';
import { appendAmount } from '../../renderer/amount.js';
import { appendSearchSorters } from '../../renderer/sorters.js';
import { athenaInfiniteSpinner } from '../../renderer/athena-infinite-spinner.js';
import checkActivePage from '../helpers/format-data-object.js';
import lazyLoad from '../../../global/helpers/lazy-loading.js';
import didYouMean from "../../../global/did-you-mean/did-you-mean.js";

/**
 * Fetch More Data for Next Page
 */
function fetchMoreDataNext() {

    // Added spinner
    athenaConfigOptions.showSpinner = true;
    athenaInfiniteSpinner();

    //Forming Data Object
    const data = {
        'service': 'search/data',
        'athenaUid': athenaConfigOptions.athenaUid,
        'search': 0,
        'page': athenaConfigOptions.nextPage,
        'q': athenaConfigOptions.searchQuery
    }

    if(athenaConfig.isCustomerLoyalty) {
        data['customer_group_id'] = athenaConfigOptions.customerGroupID;
    }

    //Get URL Search params and add it to data
    const queries = getUrlSearchParams();
    for (const queryKey in queries) {
        if(queryKey !== 'page'){
            data[queryKey] = queries[queryKey];
        }
    }

    const {
        isVisualSearch,
        isCategory
    } = checkActivePage(data);

    if(athenaConfig.hybridSearchModel && !isVisualSearch && !isCategory) {
        data['hybrid_search_model_type'] = athenaConfig.hybridSearchModel;
    }

    isVisualSearch
        .then((visual) => {
            if(athenaConfig.hybridSearchModel && !visual && !isCategory) {
                data['hybrid_search_model_type'] = athenaConfig.hybridSearchModel;
            }

            athenaFetchApi(data, true)
                .then(response => {
                    appendSearchProducts(
                        response.data.products.results,
                        athenaConfigOptions.searchProductContainer,
                        false,
                        isCategory,
                        response.data.best_match_size,
                        response.data.products.amounts,
                        true
                    );

                    athenaConfigOptions.nextPage = response.data.products.amounts.next_page;
                    athenaConfigOptions.currentPage = response.data.products.amounts.current_page;
                    athenaConfigOptions.lastPage = response.data.products.amounts.last_page;
                    appendAmount(response.data.products.amounts);
                    appendSearchSorters(response.data.products.sorters, response.data.products.results);

                    athenaConfigOptions.scrollStatus = true;

                    const products = document.querySelectorAll('.product-item');
                    const page = response.data.products.amounts.current_page

                    products.forEach((product,index)=>{
                        if (index >= products.length - response.data.products.amounts.per_page){
                            product.setAttribute('data-page', page);
                        }
                    });
                    //Add Observer To Products
                    addObserverToProducts(page);
                    // Remove spinner
                    athenaConfigOptions.showSpinner = false;
                    // Add Spinner
                    athenaInfiniteSpinner();
                    //Append Products End
                    appendProductEnd(response.data.products.amounts.current_page, response.data.products.amounts.last_page);
                    //Lazy Loading Images
                    lazyLoad('.athena-product-image-photo');

                    //Handle Did you mean
                    didYouMean(
                        response.data?.did_you_mean,
                        document.querySelector('#athena-landing-page__container') ?? null,
                        'search'
                    );
                });
        });
}

//Exporting all Functions
export {
    fetchMoreDataNext
}