import { isNothing } from "@jet/environment";
import * as editorialMediaUtil from "./editorial-media-util";
import * as mediaAttributes from "../../foundation/media/attributes";
import * as mediaDataFetching from "../../foundation/media/data-fetching";
import * as mediaDataStructure from "../../foundation/media/data-structure";
import * as mediaRelationship from "../../foundation/media/relationships";
import * as metricsHelpersLocation from "../../common/metrics/helpers/location";
import * as metricsHelpersPage from "../../common/metrics/helpers/page";
import * as metricsHelpersUtil from "../../common/metrics/helpers/util";
import * as models from "../../api/models";
import * as onDevicePersonalization from "../../common/personalization/on-device-personalization";
import * as refresh from "../../common/refresh/page-refresh-controller";
import * as serverData from "../../foundation/json-parsing/server-data";
import * as sharing from "../../common/sharing";
import * as shelfBatching from "../../common/grouping/shelf-batching";
import { createBaseShelfToken } from "./editorial-page-shelf-token";
import { buildEditorialShelf } from "./editorial-page-shelf-builder";
import { buildArcadeLockup } from "./editorial-page-shelf-builder/editorial-page-arcade-lockup-builder";
import { shelfForTermsAndConditions } from "../grouping/grouping-common";
import { EditorialShelfType } from "./editorial-page-types";
/**
 * Returns the number of shelves to hydrate on first load
 */
export function pageSparseCount(objectGraph) {
    if (objectGraph.client.isWeb) {
        // Returning `null` will avoid `Request` from setting the count at all
        return null;
    }
    else {
        return 5;
    }
}
/**
 * Returns the number of hydrated items in the hydrated shelves
 */
export function pageSparseLimit(objectGraph) {
    return 12;
}
/**
 * Modify request for a items fetched for grouping shelf items. (i.e. individual IDs).
 * This should be ideally be in grouping builder's `prepareRequest`, but that would change how url-driven requests are configured.
 * @param objectGraph
 * @param request Request to modify.
 */
export function prepareMAPIRequest(objectGraph, request) {
    const baseAttributes = ["editorialArtwork", "editorialVideo", "editorialClientParams"];
    const editorialItemsAttributes = [
        ...baseAttributes,
        "showExpectedReleaseDate",
        "expectedReleaseDateDisplayFormat",
        "enrichedEditorialNotes",
        "shortEditorialNotes",
    ];
    const editorialPagesAttributes = [...baseAttributes, "enrichedEditorialNotes"];
    const contentAttributes = [
        ...baseAttributes,
        "minimumOSVersion",
        "screenshotsByType",
        "videoPreviewsByType",
        "expectedReleaseDateDisplayFormat",
        "isAppleWatchSupported",
        "minimumOSVersion",
        "compatibilityControllerRequirement",
    ];
    if (objectGraph.appleSilicon.isSupportEnabled) {
        contentAttributes.push("macRequiredCapabilities");
    }
    if (objectGraph.client.isMac) {
        contentAttributes.push("hasMacIPAPackage");
    }
    if (objectGraph.client.isVision) {
        request.addingRelationshipLimit("editorial-shelves-collection:contents", 100);
    }
    if (objectGraph.client.isWeb) {
        request.addingRelationshipLimit("editorial-shelves-collection:contents", 20);
    }
    const appsAttributes = [...contentAttributes];
    const features = ["personalization", "supportsCustomTextColor"];
    request
        .includingAgeRestrictions()
        .includingAdditionalPlatforms(mediaDataFetching.defaultAdditionalPlatformsForClient(objectGraph))
        .enablingFeatures(features)
        .includingRelationshipsForUpsell(true)
        .includingScopedAttributes("editorial-items", editorialItemsAttributes)
        .includingScopedAttributes("editorial-pages", editorialPagesAttributes)
        .includingScopedAttributes("apps", appsAttributes);
}
export function shareSheetActionFromData(objectGraph, editorialPageData) {
    var _a;
    const url = mediaAttributes.attributeAsString(editorialPageData, "url");
    const title = mediaAttributes.attributeAsString(editorialPageData, "editorialNotes.name");
    if (serverData.isNull(url) || serverData.isNull(title)) {
        return null;
    }
    const subtitle = objectGraph.loc.string("SHARE_EDITORIAL_PAGE_SUBTITLE");
    const artwork = (_a = editorialMediaUtil.editorialMediaDataForPlacement(objectGraph, editorialPageData, editorialMediaUtil.EditorialMediaPlacement.EditorialPage)) === null || _a === void 0 ? void 0 : _a.artwork;
    // Create share sheet model (bail out if unable to do so)
    const shareData = sharing.shareSheetDataForGenericPage(objectGraph, title, url, subtitle, null, artwork);
    if (isNothing(shareData)) {
        return null;
    }
    const activities = sharing.shareSheetActivitiesForGenericPage(objectGraph, url);
    return new models.ShareSheetAction(shareData, activities);
}
export async function renderPage(objectGraph, data, parameters) {
    var _a, _b;
    const editorialPageData = mediaDataStructure.dataFromDataContainer(objectGraph, data);
    if (!serverData.isDefinedNonNullNonEmpty(editorialPageData)) {
        return null;
    }
    const canvasData = mediaRelationship.relationshipCollection(editorialPageData, "canvas");
    if (!serverData.isDefinedNonNullNonEmpty(canvasData)) {
        return null;
    }
    let pageType = "Editorial";
    const typeFromServer = serverData.asString(editorialPageData, "type");
    if (typeFromServer === "tags") {
        pageType = "TagRoom";
    }
    const metricsPageInformation = metricsHelpersPage.metricsPageInformationFromMediaApiResponse(objectGraph, pageType, editorialPageData.id, data);
    const metricsLocationTracker = metricsHelpersLocation.newLocationTracker();
    const onDevicePersonalizationMetricsData = onDevicePersonalization.metricsData(objectGraph);
    metricsPageInformation.recoMetricsData = metricsHelpersUtil.combinedRecoMetricsDataFromMetricsData(metricsPageInformation.recoMetricsData, null, onDevicePersonalizationMetricsData);
    const pageRefreshController = refresh.newPageRefreshControllerFromResponse(data);
    const { isArcadePage } = parameters;
    const shelves = [];
    let pageData = null;
    let arcadeLockup = null;
    if (serverData.isDefinedNonNull(editorialPageData.attributes)) {
        pageData = {
            id: editorialPageData.id,
            type: editorialPageData.type,
            attributes: editorialPageData.attributes,
            relationships: editorialPageData.relationships,
            meta: editorialPageData.meta,
        };
    }
    else {
        return null;
    }
    let hasUpsellbreakout = false;
    for (const shelfData of canvasData) {
        const shelfIndex = shelves.length;
        const shelfToken = createBaseShelfToken(objectGraph, pageData.id, shelfData, isArcadePage, shelfIndex, metricsPageInformation, metricsLocationTracker);
        const shelf = buildEditorialShelf(objectGraph, pageData, shelfToken);
        if (serverData.isNull(shelf)) {
            continue;
        }
        if (shelves.length === 0) {
            const existingPresentationHints = shelf.presentationHints;
            shelf.presentationHints = {
                ...existingPresentationHints,
                isFirstShelf: true,
            };
        }
        if (shelfToken.type === EditorialShelfType.Upsell) {
            hasUpsellbreakout = true;
        }
        if (shelf.contentType === "upsellBreakout") {
            arcadeLockup = buildArcadeLockup(objectGraph, shelfToken);
        }
        shelves.push(shelf);
    }
    const page = isArcadePage ? new models.ArcadePage(shelves) : new models.GenericPage(shelves);
    page.title = hasUpsellbreakout
        ? null
        : (_a = mediaAttributes.attributeAsString(editorialPageData, "editorialNotes.name")) !== null && _a !== void 0 ? _a : mediaAttributes.attributeAsString(editorialPageData, "name");
    page.canonicalURL = mediaAttributes.attributeAsString(editorialPageData, "url");
    page.shareAction = shareSheetActionFromData(objectGraph, editorialPageData);
    page.pageRefreshPolicy = refresh.pageRefreshPolicyForController(objectGraph, pageRefreshController);
    // Create the ArcadeLockup for Arcade's sticky header
    if (isArcadePage && serverData.isDefinedNonNull(arcadeLockup)) {
        page.subscriptionLockup = arcadeLockup;
    }
    if (isArcadePage) {
        metricsPageInformation.isCrossfireReferralCandidate = true;
    }
    metricsHelpersPage.addMetricsEventsToPageWithInformation(objectGraph, page, metricsPageInformation);
    if (objectGraph.client.isVision) {
        page.presentationOptions.push("prefersRevealingPageTitleWhenNotRoot");
    }
    const isLastShelfSeeAllGames = ((_b = shelves[shelves.length - 1]) === null || _b === void 0 ? void 0 : _b.contentType) === "arcadeFooter";
    if (objectGraph.client.deviceType !== "watch" &&
        objectGraph.client.deviceType !== "tv" &&
        !isLastShelfSeeAllGames) {
        const url = objectGraph.bag.termsAndConditionsURL;
        if (!serverData.isNull(url)) {
            const termsAndConditionsShelf = shelfForTermsAndConditions(objectGraph, url);
            shelves.push(termsAndConditionsShelf);
        }
    }
    if (shelves.length > 0) {
        const isLargeHeroBreakout = shelves[0].contentType === "largeHeroBreakout";
        const isUpsell = shelves[0].contentType === "upsellBreakout";
        const isHeroCarousel = shelves[0].contentType === "heroCarousel";
        const isMediaPageHeader = shelves[0].contentType === "mediaPageHeader";
        const shouldOverlayPageHeader = isLargeHeroBreakout || isUpsell || isHeroCarousel || isMediaPageHeader;
        if (shouldOverlayPageHeader && !preprocessor.GAMES_TARGET) {
            page.presentationOptions.push("prefersOverlayedPageHeader");
        }
        if (isMediaPageHeader) {
            page.presentationOptions.push("prefersNonStandardBackButton");
            page.presentationOptions.push("prefersHiddenPageTitle");
        }
    }
    shelfBatching.addBatchGroupsToPage(page);
    return page;
}
//# sourceMappingURL=editorial-page-controller-util.js.map