<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="/js-test-resources/js-test.js"></script>
    <script src="resources/util.js"></script>
</head>
<body onload="runTest()">
<script>
    description("Tests that existing third-party cookies are not blocked when ITP is off.");
    jsTestIsAsync = true;

    const partitionHost = "127.0.0.1:8000";
    const partitionOrigin = "http://" + partitionHost;
    const thirdPartyOrigin = "http://localhost:8000";
    const resourcePath = "/resourceLoadStatistics/resources";
    const thirdPartyBaseUrl = thirdPartyOrigin + resourcePath;
    const firstPartyCookieName = "firstPartyCookie";
    const subPathToSetFirstPartyCookie = "/set-cookie.py?name=" + firstPartyCookieName + "&value=value";
    const returnUrl = partitionOrigin + "/resourceLoadStatistics/no-third-party-cookie-blocking-when-itp-is-off.html";
    const subPathToGetCookies = "/get-cookies.py?name1=" + firstPartyCookieName;

    function openIframe(url, onLoadHandler) {
        const element = document.createElement("iframe");
        if (onLoadHandler) {
            element.onload = onLoadHandler;
        }
        element.src = url;
        document.body.appendChild(element);
    }

    function runTest() {
        switch (document.location.hash) {
            case "":
                document.location.hash = "step2";
                testRunner.dumpChildFramesAsText();
                // Enable the flag even though ITP will be turned off.
                testRunner.setStatisticsShouldBlockThirdPartyCookies(true, function () {
                    testRunner.setStatisticsEnabled(false);
                    runTest();
                });
                break;
            case "#step2":
                // Set first-party cookie for localhost.
                document.location.href = thirdPartyBaseUrl + subPathToSetFirstPartyCookie + "#" + returnUrl + "#step3";
                break;
            case "#step3":
                // Check that the cookie is not blocked for localhost under 127.0.0.1.
                openIframe(thirdPartyBaseUrl + subPathToGetCookies + "&message=Should receive its cookie.", function() {
                    testRunner.setStatisticsEnabled(true);
                    testRunner.setStatisticsShouldBlockThirdPartyCookies(false, function() {
                        finishJSTest();
                    });
                });
                break;
        }
    }
</script>
</body>
</html>