import * as models from "../../../api/models";
import * as serverData from "../../../foundation/json-parsing/server-data";
import * as mediaAttributes from "../../../foundation/media/attributes";
import * as mediaDataStructure from "../../../foundation/media/data-structure";
import * as mediaRelationship from "../../../foundation/media/relationships";
import * as content from "../../content/content";
import * as flowPreview from "../../content/flow-preview";
import * as lockupsEditorialContext from "../../lockups/editorial-context";
import * as metricsHelpersClicks from "../../metrics/helpers/clicks";
import * as metricsHelpersImpressions from "../../metrics/helpers/impressions";
import * as metricsHelpersLocation from "../../metrics/helpers/location";
import * as placeholders from "../../placeholders/placeholders";
import { GroupingShelfController } from "./grouping-shelf-controller";
import * as groupingShelfControllerCommon from "./grouping-shelf-controller-common";
import { defaultLayoutSize } from "../../../foundation/media/data-fetching";
import { isSome } from "@jet/environment";
export class GroupingTagBrickShelfController extends GroupingShelfController {
    // region Constructors
    constructor() {
        super("GroupingTagBrickShelfController");
        this.supportedFeaturedContentIds = new Set([
            584 /* groupingTypes.FeaturedContentID.AppStore_TagsBrick */,
            587 /* groupingTypes.FeaturedContentID.AppStore_PersonalizedTagsBrick */,
        ]);
    }
    // endregion
    // region Shelf Creation Prerequisites
    /**
     * For a given mediaApiData extract the actual shelfContents array needed to render this shelf
     *
     * @param mediaApiData The outer shelfContents object containing the shelf contents
     */
    initialShelfDataFromGroupingMediaApiData(objectGraph, mediaApiData) {
        var _a;
        if (isSome(mediaApiData)) {
            const shelfContents = (_a = mediaRelationship.relationshipCollection(mediaApiData, "contents")) !== null && _a !== void 0 ? _a : null;
            return { shelfContents: shelfContents };
        }
        return { shelfContents: null };
    }
    /**
     * For a given url that this controller handles, we should return a promise that will result in the `ShelfData`
     * needed to render this shelf
     *
     * @param objectGraph The App Store dependency graph
     * @param shelfUrl The url that this controller handled on a secondary fetch
     * @param parameters The extracted parameters from the shelf url
     */
    async secondaryShelfDataForShelfUrl(objectGraph, shelfUrl, shelfToken, parameters) {
        return await GroupingShelfController.secondaryGroupingShelfMediaApiData(objectGraph, shelfUrl, shelfToken, parameters).then((shelfData) => {
            return {
                shelfContents: shelfData.data,
            };
        });
    }
    /**
     * For a given mediaApiData create an updated shelf token that contains all the additional data for this specific shelf type
     *
     * @param objectGraph The App Store dependency graph
     * @param baseShelfToken The base grouping shelf token created by the grouping-controller
     * @param mediaApiData The outer data object containing the FC properties and data
     * @param groupingParseContext The parse context for the grouping page so far
     */
    shelfTokenFromBaseTokenAndMediaApiData(objectGraph, mediaApiData, baseShelfToken, groupingParseContext) {
        // If suppress text is not provided, default to hiding.
        let suppressText = mediaAttributes.attributeAsBoolean(mediaApiData, "suppressText");
        if (serverData.isNull(suppressText)) {
            suppressText = true;
        }
        const brickShelfToken = {
            ...baseShelfToken,
            showSupplementaryText: !suppressText,
        };
        brickShelfToken.clientIdentifierOverride = lockupsEditorialContext.clientIdentifierForEditorialContextInData(objectGraph, mediaApiData);
        return brickShelfToken;
    }
    // endregion
    // region Shelf Creation
    /**
     *
     * @param objectGraph The App Store dependency graph
     * @param shelfToken The shelf shelfToken for this current shelf creation request
     * @param shelfData The media api shelfContents array for this shelf
     * @param groupingParseContext The parse context used to generate the grouping page on the initial page load,
     * this will be missing when this controller renders a secondary or incomplete shelf fetch.
     */
    _createShelf(objectGraph, shelfToken, shelfData, groupingParseContext) {
        const items = [];
        const remainingBricks = []; // Data where metadata was missing.
        const displayStyle = serverData.asString(shelfToken.featuredContentData.attributes, "displayStyle");
        const isCategoryBrick = displayStyle === "small";
        const shelf = new models.Shelf("tagBrick");
        const layoutSize = serverData.asNumber(shelfToken.featuredContentData.attributes, "layoutStyle.layoutSize");
        shelf.rowsPerColumn = layoutSize !== null && layoutSize !== void 0 ? layoutSize : defaultLayoutSize(objectGraph);
        shelf.isHorizontal = true;
        if (isSome(shelfData.shelfContents)) {
            for (const tagData of shelfData.shelfContents) {
                const brickModel = GroupingTagBrickShelfController.createBrick(objectGraph, tagData, isCategoryBrick, shelfToken.metricsPageInformation, shelfToken.metricsLocationTracker, shelfToken, groupingParseContext);
                if (!isSome(brickModel === null || brickModel === void 0 ? void 0 : brickModel.shortEditorialDescription)) {
                    shelfToken.remainingItems.push(tagData);
                    remainingBricks.push(tagData);
                    continue;
                }
                if (isSome(brickModel)) {
                    items.push(brickModel);
                }
                metricsHelpersLocation.nextPosition(shelfToken.metricsLocationTracker);
            }
        }
        if (serverData.isDefinedNonNull(shelfToken.presentationHints)) {
            shelf.presentationHints = shelfToken.presentationHints;
        }
        if (serverData.isDefinedNonNull(shelfToken.showSupplementaryText)) {
            shelf.presentationHints = {
                ...shelf.presentationHints,
                showSupplementaryText: shelfToken.showSupplementaryText,
            };
        }
        // We don't need this in our incomplete shelf URL, so we'll preemptively remove it.
        delete shelfToken.maxItemCount;
        // Override `featuredContentData` to only have remaining bricks that must be fetched.
        if (serverData.isDefinedNonNull(serverData.traverse(shelfToken.featuredContentData, "relationships.contents.data")) &&
            isSome(shelfToken.featuredContentData.relationships)) {
            shelfToken.featuredContentData.relationships["contents"].data = remainingBricks;
        }
        // Set metadata
        shelf.title = shelfToken.title;
        shelf.subtitle = shelfToken.subtitle;
        if (isCategoryBrick) {
            const displayCount = serverData.asNumber(shelfToken.featuredContentData.attributes, "displayCount");
            shelf.items = items.slice(0, displayCount !== null && displayCount !== void 0 ? displayCount : items.length);
        }
        else {
            shelf.items = items;
        }
        // See all
        const hasSeeAll = serverData.asBooleanOrFalse(shelfToken.featuredContentData.attributes, "hasSeeAll");
        if (isCategoryBrick && hasSeeAll) {
            // Setup shelf
            const seeAllShelf = new models.Shelf("categoryBrick");
            seeAllShelf.items = items;
            seeAllShelf.presentationHints = { isSeeAllContext: true };
            // Setup Page
            const seeAllPage = new models.GenericPage([seeAllShelf]);
            seeAllPage.title = shelfToken.title;
            // Setup action
            const seeAllAction = new models.FlowAction("page");
            seeAllAction.title = objectGraph.loc.string("ACTION_SEE_ALL");
            seeAllAction.pageData = seeAllPage;
            // Connect action
            shelf.seeAllAction = seeAllAction;
            // Metrics
            metricsHelpersClicks.addClickEventToSeeAllAction(objectGraph, seeAllAction, "", {
                pageInformation: shelfToken.metricsPageInformation,
                locationTracker: shelfToken.metricsLocationTracker,
            });
        }
        // If no items should we display placeholders for this shelf?
        const willHydrateShelfLater = shelf && serverData.isNullOrEmpty(shelf.items) && shelfToken.isFirstRender;
        if (willHydrateShelfLater && placeholders.placeholdersEnabled(objectGraph)) {
            placeholders.insertPlaceholdersIntoGenericPageShelf(objectGraph, shelf, shelfToken, shelfToken.featuredContentId);
        }
        shelfToken.presentationHints = shelf.presentationHints;
        shelf.url = groupingShelfControllerCommon.createShelfTokenUrlIfNecessaryForShelf(objectGraph, shelf, shelfToken);
        return shelf;
    }
    // region Static Helpers
    static createBrick(objectGraph, brickData, searchCategoryBricks, metricsPageInformation, metricsLocationTracker, shelfToken, groupingParseContext) {
        var _a, _b, _c;
        const metricsBrickData = (_a = mediaDataStructure.metricsFromMediaApiObject(brickData)) !== null && _a !== void 0 ? _a : undefined;
        const metricsOptions = {
            targetType: searchCategoryBricks ? "tile" : "brick",
            pageInformation: metricsPageInformation,
            locationTracker: metricsLocationTracker,
            recoMetricsData: metricsBrickData,
        };
        const metadata = groupingShelfControllerCommon.metadataForTag(objectGraph, brickData, shelfToken !== null && shelfToken !== void 0 ? shelfToken : null, metricsOptions);
        if (!metadata) {
            const brickModel = new models.Brick();
            brickModel.shortEditorialDescription = mediaAttributes.attributeAsString(brickData, "name");
            return brickModel;
        }
        const brickModel = new models.Brick();
        // Setup Artwork
        const artworkOptions = {
            useCase: 18 /* content.ArtworkUseCase.GroupingBrick */,
        };
        const collectionIcons = groupingShelfControllerCommon.artworkForTags(objectGraph, brickData, 1060, 520, artworkOptions, metricsOptions);
        if (collectionIcons.length > 0) {
            const collectionIconBackgroundColor = collectionIcons[0].backgroundColor;
            brickModel.collectionIcons = collectionIcons;
            if (isSome(collectionIconBackgroundColor) && (collectionIconBackgroundColor === null || collectionIconBackgroundColor === void 0 ? void 0 : collectionIconBackgroundColor.type) === "rgb") {
                brickModel.backgroundColor =
                    (_b = content.closestTagBackgroundColorForIcon(collectionIconBackgroundColor)) !== null && _b !== void 0 ? _b : undefined;
            }
        }
        brickModel.accessibilityLabel = metadata.title;
        // Set supplementary text.
        brickModel.shortEditorialDescription = metadata.shortEditorialDescription;
        // Set action
        brickModel.clickAction = metadata.action;
        // Set personalization
        const brickFeaturedContentId = mediaAttributes.attributeAsNumber(brickData, "editorialElementKind");
        if (brickFeaturedContentId === 435 /* groupingTypes.FeaturedContentID.AppStore_MSOBrickMarker */) {
            brickModel.personalizationStyle = "mso";
        }
        // Set flow preview actions
        const contentData = mediaRelationship.relationshipData(objectGraph, brickData, "contents");
        if (serverData.isDefinedNonNull(contentData)) {
            const metricsClickOptions = metricsHelpersClicks.clickOptionsForLockup(objectGraph, contentData, metricsOptions);
            const clientIdentifierOverride = (_c = shelfToken === null || shelfToken === void 0 ? void 0 : shelfToken.clientIdentifierOverride) !== null && _c !== void 0 ? _c : null;
            brickModel.flowPreviewActionsConfiguration = flowPreview.flowPreviewActionsConfigurationForProductFromData(objectGraph, brickData, true, clientIdentifierOverride, brickModel.clickAction, metricsOptions, metricsClickOptions);
        }
        // Configure impressions
        const impressionOptions = metricsHelpersImpressions.impressionOptions(objectGraph, brickData, metadata.title, metricsOptions);
        metricsHelpersImpressions.addImpressionFields(objectGraph, brickModel, impressionOptions);
        // Safe area
        brickModel.artworkSafeArea = models.ChartOrCategorySafeArea.defaultTileArtworkSafeArea;
        brickModel.textSafeArea = models.ChartOrCategorySafeArea.defaultTileTextSafeArea;
        if (!brickModel.isValid()) {
            return null;
        }
        return brickModel;
    }
    // endregion
    // region Metrics
    /**
     * Return the shelf metrics options to use for this specific shelf. Using the base options from the grouping
     * page controller
     *
     * @param objectGraph The App Store dependency graph
     * @param shelfToken The shelf shelfToken for this current shelf creation request
     * @param baseMetricsOptions The minimum set of metrics options for this shelf, created by the
     * grouping page controller
     */
    shelfMetricsOptionsFromBaseMetricsOptions(objectGraph, shelfToken, baseMetricsOptions) {
        const shelfMetricsOptions = { ...baseMetricsOptions };
        const displayStyle = serverData.asString(shelfToken.featuredContentData.attributes, "displayStyle");
        // If this is a Category Bricks shelf, configure metrics title accordingly.
        if (displayStyle === "small") {
            shelfMetricsOptions.title = "Browse Categories";
        }
        return shelfMetricsOptions;
    }
}
//# sourceMappingURL=grouping-tag-brick-shelf-controller.js.map