import * as validation from "@jet/environment/json/validation";
import * as models from "../../../api/models";
import * as serverData from "../../../foundation/json-parsing/server-data";
import * as mediaAttributes from "../../../foundation/media/attributes";
import { Path, Protocol } from "../../../foundation/network/url-constants";
import * as contentAttributes from "../../content/attributes";
import * as sad from "../../content/sad";
import * as productPageUtil from "../product-page-util";
import * as informationShelf from "./annotations/annotations";
import * as metricsHelpersClicks from "../../metrics/helpers/clicks";
import { isSome } from "@jet/environment/types/optional";
import { makeEulaPageIntent } from "../../../api/intents/eula-page-intent";
/**
 * Create a links shelf for the product page.
 *
 * @param data The raw data response for a product page JSON fetch.
 * @param shelfMetrics The product page shelf metrics.
 * @param isPurchased Whether the links are for a user who has purchased the product.
 * @param isFreeProduct Whether the offer is for a free product.
 * @param isArcadeProduct Whether the product is an Arcade product.
 * @returns A links shelf.
 */
export function create(objectGraph, data, shelfMetrics, isPurchased, isFreeProduct, isArcadeProduct) {
    return validation.context("create", () => {
        if (serverData.isNullOrEmpty(data)) {
            return null;
        }
        if (objectGraph.client.isTV) {
            return tvLinksShelf(objectGraph, data, isFreeProduct, shelfMetrics);
        }
        return standardLinksShelf(objectGraph, data, shelfMetrics, isPurchased, isArcadeProduct);
    });
}
/**
 * Determines the URL to use for the EULA page.
 * @param {Data} data The data for the product.
 * @returns {string} The string form of the URL for the EULA page, or `null` if the data is undefined or
 * null.
 */
function eulaUrlFromData(objectGraph, data) {
    const resourceId = data.id;
    const resourceType = data.type;
    if (!(serverData.isDefinedNonNull(data) &&
        serverData.isDefinedNonNull(resourceId) &&
        serverData.isDefinedNonNull(resourceType))) {
        return null;
    }
    return `${Protocol.internal}:/${Path.eula}?resourceType=${resourceType}&resourceId=${resourceId}`;
}
export function privacyPolicyUrlFromData(objectGraph, data) {
    const resourceId = data.id;
    if (!(serverData.isDefinedNonNull(data) && serverData.isDefinedNonNull(resourceId))) {
        return null;
    }
    return `${Protocol.internal}:/${Path.privacyPolicy}?resourceId=${resourceId}`;
}
function tvEulaUrlFromData(objectGraph, data) {
    const resourceId = data.id;
    const resourceType = data.type;
    if (!(serverData.isDefinedNonNull(data) &&
        serverData.isDefinedNonNull(resourceId) &&
        serverData.isDefinedNonNull(resourceType))) {
        return null;
    }
    return `${Protocol.internal}:/${Path.tvEula}?resourceType=${resourceType}&resourceId=${resourceId}`;
}
function safetyComplianceUrlForContent(objectGraph, pageContent) {
    if (serverData.isNullOrEmpty(pageContent)) {
        return null;
    }
    return `${Protocol.internal}:/${Path.safetyCompliance}?pageContent=${encodeURIComponent(pageContent)}`;
}
function reportAProblemUrlFromData(objectGraph, data) {
    const resourceId = data.id;
    const reportAProblemURL = objectGraph.bag.productPageReportProblemURL;
    if (!(serverData.isDefinedNonNull(resourceId) && serverData.isDefinedNonNull(reportAProblemURL))) {
        return null;
    }
    return reportAProblemURL.replace("{productId}", resourceId);
}
/**
 * The links shelf for TV deviceTypes.
 * @param data The product data to use
 * @param isFreeProduct Whether the offer is for a free product.
 * @param shelfMetrics The current product page shelf metrics
 * @returns {models.Shelf} The shelf of links.
 */
function tvLinksShelf(objectGraph, data, isFreeProduct, shelfMetrics) {
    return validation.context("tvLinksShelf", () => {
        const shelf = new models.Shelf("titledButtonStack");
        const links = [];
        const moreInformationShelf = informationShelf.create(objectGraph, data, false, shelfMetrics, null, false, isFreeProduct, true);
        moreInformationShelf.presentationHints = { isSeeAllContext: true };
        const moreInformationPage = new models.GenericPage([moreInformationShelf]);
        moreInformationPage.title = mediaAttributes.attributeAsString(data, "name");
        if (objectGraph.client.isTV) {
            moreInformationPage.presentationOptions.push("prefersIndirectTouch");
        }
        const moreInformationAction = new models.FlowAction("page");
        moreInformationAction.presentationContext = "presentModalBlur";
        moreInformationAction.pageData = moreInformationPage;
        const moreInformationButton = new models.TitledButton(objectGraph.loc.string("MORE_INFORMATION"), moreInformationAction);
        links.push(moreInformationButton);
        const hasPrivacyPolicy = contentAttributes.contentAttributeAsBooleanOrFalse(objectGraph, data, "hasPrivacyPolicyText");
        if (hasPrivacyPolicy) {
            const url = privacyPolicyUrlFromData(objectGraph, data);
            if (url) {
                const text = objectGraph.loc.string("PRIVACY_POLICY");
                const action = new models.FlowAction("unknown");
                action.pageUrl = url;
                const button = new models.TitledButton(text, action);
                links.push(button);
            }
        }
        const hasLicenseAgreement = mediaAttributes.attributeAsBoolean(data, "hasEula");
        if (hasLicenseAgreement) {
            const url = tvEulaUrlFromData(objectGraph, data);
            if (url) {
                const text = objectGraph.loc.string("LICENSE_AGREEMENT");
                const action = new models.FlowAction("unknown");
                action.pageUrl = url;
                const button = new models.TitledButton(text, action);
                links.push(button);
            }
        }
        const traderData = contentAttributes.contentAttributeAsDictionary(objectGraph, data, "sellerInfo");
        const safetyAndComplianceURL = serverData.asString(traderData, "safetyAndComplianceUrl");
        if ((safetyAndComplianceURL === null || safetyAndComplianceURL === void 0 ? void 0 : safetyAndComplianceURL.length) > 0) {
            const url = safetyComplianceUrlForContent(objectGraph, safetyAndComplianceURL);
            if (isSome(url)) {
                const text = objectGraph.loc.string("ProductPage.Section.SafetyAndCompliance.Title");
                const action = new models.FlowAction("unknown");
                action.pageUrl = url;
                const button = new models.TitledButton(text, action);
                links.push(button);
            }
        }
        const stack = new models.TitledButtonStack(links);
        // On compact width, we want to place a line break after each button.
        stack.compactLineBreaks = stack.buttons.map((value, index) => index);
        shelf.items = [stack];
        if (productPageUtil.isShelfBased(objectGraph)) {
            shelf.background = {
                type: "darkOverlay",
            };
        }
        shelfMetrics.addImpressionsToShelf(objectGraph, shelf, "links");
        return shelf;
    });
}
/**
 * The links shelf for all deviceTypes except TV.
 * @param data The product data to use
 * @param shelfMetrics The current product page shelf metrics
 * @param isPurchased Whether the links are to be displayed on a purchased product page
 * @param isArcadeProduct Whether the product is an Arcade product
 * @returns {models.Shelf} The shelf of links.
 */
function standardLinksShelf(objectGraph, data, shelfMetrics, isPurchased, isArcadeProduct) {
    return validation.context("standardLinksShelf", () => {
        const shelf = new models.Shelf("productPageLink");
        const { metricsPageInformation, locationTracker } = shelfMetrics;
        const links = [];
        const isWeb = objectGraph.client.isWeb;
        if (objectGraph.client.deviceType !== "mac") {
            const developerWebsiteUrl = contentAttributes.contentAttributeAsString(objectGraph, data, "websiteUrl");
            if (developerWebsiteUrl) {
                const action = new models.ExternalUrlAction(developerWebsiteUrl, false);
                const text = objectGraph.loc.string("DEVELOPER_WEBSITE");
                if (isWeb) {
                    metricsHelpersClicks.addClickEventToAction(objectGraph, action, {
                        id: "DeveloperWebsite",
                        actionDetails: {
                            type: "developer",
                        },
                        actionType: "navigate",
                        locationTracker,
                        pageInformation: metricsPageInformation,
                    }, false, "link");
                }
                links.push(new models.ProductPageLink(text, action, "safari" /* models.ProductPageLinkImageName.developer */));
            }
        }
        const privacyPolicyUrl = contentAttributes.contentAttributeAsString(objectGraph, data, "privacyPolicyUrl");
        if (privacyPolicyUrl) {
            const action = new models.ExternalUrlAction(privacyPolicyUrl, false);
            if (isWeb) {
                metricsHelpersClicks.addClickEventToAction(objectGraph, action, {
                    id: "LinkToPrivacyPolicy",
                    actionType: "navigate",
                    locationTracker,
                    pageInformation: metricsPageInformation,
                }, false, "link");
            }
            const text = objectGraph.loc.string("PRIVACY_POLICY");
            links.push(new models.ProductPageLink(text, action, "hand.raised.fill" /* models.ProductPageLinkImageName.privacy */));
        }
        const hasLicenseAgreement = mediaAttributes.attributeAsBoolean(data, "hasEula");
        if (hasLicenseAgreement) {
            const url = eulaUrlFromData(objectGraph, data);
            if (url) {
                const flowPage = isWeb ? "licenseAgreement" : "page";
                const action = new models.FlowAction(flowPage);
                action.pageUrl = url;
                if (isWeb) {
                    const resourceId = data.id;
                    const resourceType = data.type;
                    // web presents this data in a modal
                    action.presentationContext = "presentModal";
                    action.destination = makeEulaPageIntent({
                        resourceId,
                        resourceType: resourceType,
                    });
                    metricsHelpersClicks.addClickEventToAction(objectGraph, action, {
                        id: "LicenseAgreement",
                        actionType: "navigate",
                        locationTracker,
                        pageInformation: metricsPageInformation,
                    }, false, "link");
                }
                const text = objectGraph.loc.string("LICENSE_AGREEMENT");
                links.push(new models.ProductPageLink(text, action, "doc.plaintext" /* models.ProductPageLinkImageName.eula */));
            }
        }
        const traderData = contentAttributes.contentAttributeAsDictionary(objectGraph, data, "sellerInfo");
        const safetyAndComplianceURL = serverData.asString(traderData, "safetyAndComplianceUrl");
        if ((safetyAndComplianceURL === null || safetyAndComplianceURL === void 0 ? void 0 : safetyAndComplianceURL.length) > 0) {
            const action = new models.ExternalUrlAction(safetyAndComplianceURL, false);
            const text = objectGraph.loc.string("ProductPage.Section.SafetyAndCompliance.Title");
            links.push(new models.ProductPageLink(text, action, "checkmark.seal" /* models.ProductPageLinkImageName.safetyAndCompliance */));
        }
        // We want to show the report-a-problem link for apps that are purchased and only SAD apps that are specified by the bag.
        // Because isPurchased contains both SAD and non SAD apps, we need a few additional checks.
        const clientSupportsReportAProblem = objectGraph.client.isMac || objectGraph.client.isiOS || objectGraph.client.isVision;
        const reportProblemSADSubscriptionArray = objectGraph.bag.productPageReportProblemSADSubscriptionArray;
        const adamID = data.id;
        const isDeletableSystemAppWithSub = reportProblemSADSubscriptionArray.includes(adamID);
        const isSystemApp = sad.systemApps(objectGraph).isSystemAppFromData(data);
        // Check if the adamID is a bundle id.
        const isBundle = data.type === "app-bundles";
        // We only want purchased apps that are not system apps
        const isPurchasedAppNotSAD = isPurchased && !isSystemApp;
        // We do not support report a problem for second party apps
        const isSecondPartyApp = objectGraph.bag.productPageReportProblemSecondPartyAppArray.includes(adamID);
        const shouldShowRAPLinkInShelf = !isBundle &&
            !isSecondPartyApp &&
            !isArcadeProduct &&
            clientSupportsReportAProblem &&
            objectGraph.bag.reportProblemEnabled &&
            (isDeletableSystemAppWithSub || isPurchasedAppNotSAD);
        if (shouldShowRAPLinkInShelf) {
            const reportAProblemUrl = reportAProblemUrlFromData(objectGraph, data);
            if ((reportAProblemUrl === null || reportAProblemUrl === void 0 ? void 0 : reportAProblemUrl.length) > 0) {
                const action = new models.ExternalUrlAction(reportAProblemUrl, false);
                const text = objectGraph.loc.string("REPORT_A_PROBLEM");
                // We never want to filter out SAD apps based on purchase history
                const adamIdForPurchaseHistoryFilter = isDeletableSystemAppWithSub ? null : adamID;
                const link = new models.ProductPageLink(text, action, "exclamationmark.triangle" /* models.ProductPageLinkImageName.reportAProblem */, adamIdForPurchaseHistoryFilter);
                links.push(link);
            }
        }
        if (links && links.length > 0) {
            shelf.items = links;
        }
        shelfMetrics.addImpressionsToShelf(objectGraph, shelf, "links");
        return shelf;
    });
}
//# sourceMappingURL=links-shelf.js.map