import dayjs from "dayjs";
import React from "react";
import { RuntimeContext } from "@qorebase/app-component";
export const timeseriesPayloadGenerator = (payload, timeColumnName, type, format, valuesKeys) => {
    return payload.map((value, idx) => (Object.assign(Object.assign(Object.assign({}, value), convertTimeSeriesNullValue(value, valuesKeys || [])), { [timeColumnName]: type === "quarter" && format === "option1"
            ? `Qtr ${idx + 1}`
            : type === "quarter" && format === "option2"
                ? `Quarter ${idx + 1}`
                : dayjs(value[timeColumnName]).format(format || "D/MM/YYYY") })));
};
const convertTimeSeriesNullValue = (payload, valuesKeys) => {
    const newPayload = {};
    for (const key of valuesKeys) {
        payload[key] === null
            ? (newPayload[key] = "0")
            : (newPayload[key] = payload[key]);
    }
    return newPayload;
};
export const useTimeSeriesSource = (source) => {
    const insights = RuntimeContext.useSelectState((state) => state.schema.insights);
    const insight = React.useMemo(() => source ? insights.find((insight) => insight.name === source) : undefined, [insights, source]);
    const isDateInsight = React.useMemo(() => {
        if (insight) {
            return !!insight.columns.find((col) => col.type === "datetime");
        }
        return false;
    }, [insight]);
    const timeseriesColumn = React.useMemo(() => {
        if (!isDateInsight)
            return "";
        return insight.columns.find((col) => col.type === "datetime").name;
    }, [isDateInsight]);
    const timeSeriesType = React.useMemo(() => {
        if (!isDateInsight)
            return "none";
        const datetimeColumn = insight.columns.find((col) => col.type === "datetime");
        const interval = insight.insight.groups[datetimeColumn.name].as.interval;
        if (interval) {
            const [intervalCount, intervalType] = interval;
            switch (intervalType) {
                case "month":
                    return intervalCount === 1 ? "month" : "quarter";
                case "year":
                    return "year";
                case "day":
                default:
                    return "day";
            }
        }
    }, [insight, isDateInsight]);
    return { isTimeseries: isDateInsight, timeseriesColumn, timeSeriesType };
};
//# sourceMappingURL=timeseries.js.map