"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useIndices = void 0;
const react_1 = __importDefault(require("react"));
const useReactifySearchContext_1 = require("./useReactifySearchContext");
const useIndices = () => {
    const { config, options } = (0, useReactifySearchContext_1.useReactifySearchContext)();
    const shopName = options.shopifyPermanentDomain.replace(".myshopify.com", "");
    const [indices, setIndices] = react_1.default.useState([]);
    const indexNameFormat = (indexName) => {
        let indexNameFormatted = indexName;
        try {
            const indexDate = indexName.split(`${shopName}-`)[1];
            indexNameFormatted = `${shopName} ${new Date(parseInt(indexDate)).toLocaleString()} (${indexDate})`;
        }
        catch (error) {
            console.error(error);
        }
        return indexNameFormatted;
    };
    react_1.default.useEffect(() => {
        (() => __awaiter(void 0, void 0, void 0, function* () {
            const response = yield fetch(`${config.endpoint}/_cat/indices?format=json`, {
                headers: {
                    "x-reactify-index": config.index,
                    "x-reactify-skip-cache": "true",
                },
            }).then((response) => response.json());
            const regexp = new RegExp(`${shopName}-[0-9]`);
            setIndices(response
                .map((item) => item.index)
                .filter((item) => regexp.test(item))
                .sort((a, b) => (a > b ? -1 : 1)));
        }))();
    }, [config.endpoint]);
    return {
        indices: indices,
        indexNameFormat: indexNameFormat,
    };
};
exports.useIndices = useIndices;
//# sourceMappingURL=useIndices.js.map