import * as onDevicePersonalizationGroupingProcessing from "./on-device-personalization-grouping-processing";
import * as onDevicePersonalizationProcessing from "./on-device-personalization-processing";
import * as serverData from "../../foundation/json-parsing/server-data";
/**
 * Accepts an array of data blobs, and returns a subset of those original data blobs which is personalized to the user.
 * In the case where personalization is disabled, or any personalized data blobs will instead be filtered out.
 *
 * @param placement Placement of the personalized items for on-device personalization
 * @param dataItems The input list of data blobs.
 * @param includeItemsWithNoPersonalizationData Whether to include data which no personalizationData meta is present.
 * @param personalizationDataContainer The data container to use for personalizing the data.
 * @param allowUnmatchedFallbackResults Whether to allow fallback results to be included in the results. This will only be utilised in order to reach a preferredResultCount.
 * @param preferredResultCount The preferred number of items to be included in the results.
 * @param parentAppId An optional appID, which is the parent for all the dataItems. Currently only used for search.
 * @param diversify An optional flag that determines if we should diverse the personalized results on the basis of server side apps ranking
 * @returns The relevant list of data blobs.
 */
export function personalizeDataItems(objectGraph, placement, dataItems, includeItemsWithNoPersonalizationData, personalizationDataContainer, allowUnmatchedFallbackResults = false, preferredResultCount, parentAppId, diversify) {
    if (isPersonalizationAvailable(objectGraph)) {
        switch (placement) {
            case "groupingAppEvent":
                return personalizeGroupingDataItems(objectGraph, dataItems, includeItemsWithNoPersonalizationData, personalizationDataContainer, diversify);
            default:
                return onDevicePersonalizationProcessing.personalizeDataItems(objectGraph, dataItems, personalizationDataContainer, includeItemsWithNoPersonalizationData, allowUnmatchedFallbackResults, preferredResultCount, parentAppId, diversify);
        }
    }
    else {
        return onDevicePersonalizationProcessing.removePersonalizedDataItems(objectGraph, dataItems, preferredResultCount);
    }
}
/**
 * Accepts an array of data blobs, and returns a subset of those original data blobs which is personalized to the user.
 * In the case where personalization is disabled, or any personalized data blobs will instead be filtered out.
 *
 * @param dataItems The input list of data blobs.
 * @param includeItemsWithNoPersonalizationData Whether to include data which no personalizationData meta is present.
 * @param personalizationDataContainer The data container to use for personalizing the data.
 * @param diversify An optional flag that determines if we should diverse the personalized results on the basis of server side apps ranking
 * @returns The relevant list of data blobs.
 */
function personalizeGroupingDataItems(objectGraph, dataItems, includeItemsWithNoPersonalizationData, personalizationDataContainer, diversify) {
    var _a, _b;
    // We must filter out non app-event items in order to avoid moving their positions
    // when contingent_offers_personalization is turned off
    let appEventsOnlyDataItems = dataItems;
    let wereItemsRemoved = false;
    const nonAppEventIndexes = [];
    if (!objectGraph.featureFlags.isEnabled("contingent_offers_personalization")) {
        appEventsOnlyDataItems = dataItems.filter((item, index) => {
            if (serverData.isDefinedNonNullNonEmpty(item.type) && item.type !== "app-events") {
                nonAppEventIndexes.push(index);
                return false;
            }
            return true;
        });
        wereItemsRemoved = appEventsOnlyDataItems.length !== dataItems.length;
    }
    // We fetch the information regarding the segment optimizer flow from the personalization container
    const personalizedMetricsData = personalizationDataContainer === null || personalizationDataContainer === void 0 ? void 0 : personalizationDataContainer.metricsData;
    const useSegScores = (_a = personalizedMetricsData["use_segment_scores"]) !== null && _a !== void 0 ? _a : false;
    const useOnDeviceSignals = (_b = personalizedMetricsData["use_signals"]) !== null && _b !== void 0 ? _b : false;
    let personalizedResults;
    if (useSegScores || useOnDeviceSignals) {
        personalizedResults = onDevicePersonalizationGroupingProcessing.personalizeDataItems(objectGraph, appEventsOnlyDataItems, personalizationDataContainer, diversify);
    }
    else {
        personalizedResults = onDevicePersonalizationProcessing.personalizeDataItems(objectGraph, appEventsOnlyDataItems, personalizationDataContainer, includeItemsWithNoPersonalizationData, null, null, null, diversify);
    }
    // We re-add non app-event items back into their original positions
    if (wereItemsRemoved) {
        const resultsArray = personalizedResults.personalizedData;
        nonAppEventIndexes.forEach((index) => {
            const item = dataItems[index];
            if (index < resultsArray.length) {
                resultsArray.splice(index, 0, item);
            }
            else {
                resultsArray.push(item);
            }
        });
        personalizedResults = {
            personalizedData: resultsArray,
            processingType: personalizedResults.processingType,
        };
    }
    return personalizedResults;
}
/**
 * Convenience function for determining if data personalization is available.
 */
export function isPersonalizationAvailable(objectGraph) {
    return (objectGraph.client.isiOS &&
        objectGraph.user.isOnDevicePersonalizationEnabled &&
        objectGraph.bag.enableOnDevicePersonalization);
}
/**
 * Reaches down to the native client to return the current set of on device personalization data,
 * restricted to a set of app IDs.
 *
 * @param appIds A set of appIds to restrict the personalization data to.
 * @returns The relevant set of personalization data
 */
export function personalizationDataContainerForAppIds(objectGraph, appIds) {
    if (!isPersonalizationAvailable(objectGraph)) {
        return null;
    }
    if (objectGraph.host.platform === "iOS") {
        return objectGraph.user.onDevicePersonalizationDataContainerForAppIds(Array.from(appIds));
    }
    else {
        return {
            personalizationData: {},
            metricsData: null,
        };
    }
    return null;
}
/**
 * Reaches down to the native client to return the current metrics data.
 *
 * @returns The current AMDClient metrics data
 */
export function metricsData(objectGraph) {
    if (!isPersonalizationAvailable(objectGraph)) {
        return null;
    }
    if (objectGraph.host.platform === "iOS") {
        return objectGraph.user.onDevicePersonalizationDataContainerForAppIds([]).metricsData;
    }
    else {
        return null;
    }
}
//# sourceMappingURL=on-device-personalization.js.map