import { ResultsListController } from '../common/results-list-controller.class';
import { attributeSelector } from '../common/selector-utilities';

const ATTRIBUTE = Object.freeze({
    SEARCH_INPUT: 'data-toubiz-search-query',
});

/**
 * Controls pagination and list rendering on toubiz search results view.
 */
export default class ToubizSearchResultsListController extends ResultsListController {

    /**
     * @protected
     * @param {HTMLFormElement} form
     * @returns {AjaxFormReload~options}
     */
    formReloadOptions(form) {
        const options = super.formReloadOptions(form);

        // Cancel AJAX reload if the search query has changed.
        const initialSearchQuery = this.getSearchQuery();
        options.ignoreAjaxReload = () => this.getSearchQuery() !== initialSearchQuery;

        return options;
    }

    /**
     * @private
     * @returns {string|null}
     */
    getSearchQuery() {
        const input = this.select(attributeSelector(ATTRIBUTE.SEARCH_INPUT));
        return input ? input.value : null;
    }

}
