import { isNothing } from "@jet/environment/types/optional";
import * as models from "../../../api/models";
import * as serverData from "../../../foundation/json-parsing/server-data";
import { Parameters, Path, Protocol } from "../../../foundation/network/url-constants";
import * as metricsHelpersClicks from "../../metrics/helpers/clicks";
import * as metricsHelpersImpressions from "../../metrics/helpers/impressions";
import * as metricsHelpersLocation from "../../metrics/helpers/location";
import * as searchLandingShelfController from "../landing/search-landing-shelf-controller";
/**
 * The `SearchHistoryShelfToken` type is responsible for plumbing through all
 * the data needed to render an incomplete shelf (a shelf that requires a
 * lookup) on the focus page.
 */
export class SearchHistoryShelfToken {
    constructor(title, maxItems, shelfDisplayStyle, itemDisplayStyle) {
        this.title = title;
        this.maxItems = maxItems;
        this.shelfDisplayStyle = shelfDisplayStyle;
        this.itemDisplayStyle = itemDisplayStyle;
    }
}
function encodedShelfToken(token) {
    return encodeURIComponent(JSON.stringify(token));
}
export function decodeShelfToken(json) {
    if (isNothing(json)) {
        return undefined;
    }
    return JSON.parse(decodeURIComponent(json));
}
export function createShelfWithContext(objectGraph, pageContext, shelfAttributes) {
    const token = new SearchHistoryShelfToken(shelfAttributes.title, shelfAttributes.displayCount, shelfAttributes.displayStyle, shelfAttributes.searchLandingItemDisplayStyle);
    return createShelfWithToken(objectGraph, token, pageContext.metricsPageInformation, pageContext.metricsLocationTracker, pageContext.searchHistory);
}
function createShelfItems(objectGraph, metricsPageInformation, metricsLocationTracker, itemDisplayStyle, searchHistory) {
    if (serverData.isNullOrEmpty(searchHistory)) {
        return [];
    }
    const items = [];
    for (const [historyIndex, historyItem] of searchHistory.entries()) {
        const item = createShelfItem(objectGraph, historyItem, historyIndex, metricsPageInformation, metricsLocationTracker, itemDisplayStyle);
        if (serverData.isNullOrEmpty(item)) {
            continue;
        }
        items.push(item);
        metricsHelpersLocation.nextPosition(metricsLocationTracker);
    }
    return items;
}
function createShelfURL(token) {
    return `${Protocol.internal}:/${Path.searchLandingPage}/${Path.shelf}/?${Parameters.isOnDeviceSearchHistoryShelf}=true&${Parameters.token}=${encodedShelfToken(token)}`;
}
export function createShelfWithToken(objectGraph, token, metricsPageInformation, metricsLocationTracker, searchHistory) {
    // Create Items
    const items = createShelfItems(objectGraph, metricsPageInformation, metricsLocationTracker, token.itemDisplayStyle, searchHistory);
    // Clear History Action
    const clearHistoryAction = new models.ClearSearchHistoryAction();
    clearHistoryAction.title = objectGraph.loc.string("Action.ClearSearches");
    metricsHelpersClicks.addClickEventToClearSearchHistoryAction(objectGraph, clearHistoryAction);
    // Clear History Sheet Action
    const clearHistorySheetAction = new models.SheetAction([clearHistoryAction]);
    clearHistorySheetAction.title = objectGraph.loc.string("Sheet.ClearSearches.Title");
    clearHistorySheetAction.message = objectGraph.loc.string("Sheet.ClearSearches.Message");
    clearHistorySheetAction.destructiveActionIndex = 0;
    clearHistorySheetAction.isCancelable = true;
    // Clear History Compound Action
    const clearHistoryShelfAction = new models.CompoundAction([clearHistorySheetAction]);
    clearHistoryShelfAction.title = objectGraph.loc.string("Action.Clear");
    // Shelf
    const contentType = shelfContentTypeForDisplayStyle(token.shelfDisplayStyle);
    const shelf = new models.Shelf(contentType);
    shelf.id = "onDeviceSearchHistory";
    shelf.presentationHints = { isWidthConstrained: true };
    // Header
    shelf.header = {
        title: token.title,
        accessoryAction: clearHistoryShelfAction,
    };
    // Grid
    if (shelf.contentType === "scrollablePill") {
        shelf.isHorizontal = true;
        shelf.rowsPerColumn = token.shelfDisplayStyle.layoutSize;
    }
    shelf.contentsMetadata = {
        type: "searchFocusTwoColumnList",
        numberOfColumns: items.length > 1 ? token.shelfDisplayStyle.layoutSize : 1,
    };
    // Content
    shelf.items = items;
    shelf.isHidden = serverData.isNullOrEmpty(items);
    shelf.refreshUrl = createShelfURL(token);
    return shelf;
}
function shelfContentTypeForDisplayStyle(displayStyle) {
    if (displayStyle.layout === "word_cloud" /* models.GenericSearchPageShelfDisplayStyleLayout.WordCloud */) {
        return "scrollablePill";
    }
    if (displayStyle.layoutSize === 2) {
        // MAINTAINER'S NOTE: Automatically renders as single column in AX text sizes.
        return "twoColumnList";
    }
    return "singleColumnList";
}
function createItemTitle(objectGraph, searchTerm, searchEntity) {
    if (isNothing(searchEntity)) {
        return searchTerm;
    }
    let formatLocKey;
    if (searchEntity === "developer") {
        formatLocKey = "Search.ResultsTitle.InDevelopers";
    }
    else if (searchEntity === "story") {
        formatLocKey = "Search.ResultsTitle.InStories";
    }
    else if (searchEntity === "watch") {
        formatLocKey = "Search.ResultsTitle.InWatch";
    }
    else if (searchEntity === "arcade") {
        formatLocKey = "Search.ResultsTitle.InArcade";
    }
    if (isNothing(formatLocKey)) {
        return searchTerm;
    }
    return objectGraph.loc.string(formatLocKey).replace("@@search_term@@", searchTerm);
}
function createShelfItem(objectGraph, historyItem, itemIndex, metricsPageInformation, metricsLocationTracker, displayStyle) {
    const searchTerm = historyItem.term;
    const searchEntity = historyItem.entity;
    const searchAction = searchLandingShelfController.createFocusPageSearchAction(objectGraph, createItemTitle(objectGraph, searchTerm, searchEntity), searchTerm, searchEntity, metricsLocationTracker, "recents", undefined, /// MAINTAINER'S NOTE: In the future, we could keep track of the original search source and attribute this recent search to that.
    metricsPageInformation, displayStyle);
    if (isNothing(searchAction)) {
        return null;
    }
    searchAction.id = historyItem.id;
    metricsHelpersImpressions.addImpressionFields(objectGraph, searchAction, {
        targetType: "link",
        pageInformation: metricsPageInformation,
        locationTracker: metricsLocationTracker,
        kind: "link",
        softwareType: null,
        title: historyItem.term,
        hintsEntity: historyItem.entity,
        id: `${itemIndex}`,
        idType: "sequential",
    });
    return searchAction;
}
//# sourceMappingURL=search-history-shelf.js.map