<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test to ensure non-prevalent resources can access their cookies in a third party context</title>
    <script src="/js-test-resources/js-test.js"></script>
    <script src="resources/util.js"></script>
</head>
<body>
<script>
    const partitionHost = "127.0.0.1:8000";
    const thirdPartyOrigin = "http://localhost:8000";
    const thirdPartyBaseUrl = thirdPartyOrigin + "/resourceLoadStatistics/resources";
    const firstPartyCookieName = "firstPartyCookie";
    const subPathToSetFirstPartyCookie = "/set-cookie.py?name=" + firstPartyCookieName + "&value=value";
    const fragmentWithReturnUrl = "http://127.0.0.1:8000/resourceLoadStatistics/non-prevalent-resources-can-access-cookies-in-a-third-party-context.html";
    const subPathToGetCookies = "/get-cookies.py?name1=" + firstPartyCookieName;

    function finishTest() {
        setEnableFeature(false, function() {
            testRunner.notifyDone();
        });
    }

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

    function runTest() {
        switch (document.location.hash) {
            case "#step1":
                // Set a first-party cookie for localhost.
                document.location.href = thirdPartyBaseUrl + subPathToSetFirstPartyCookie + "#" + fragmentWithReturnUrl + "#step2";
                break;
            case "#step2":
                // Load localhost under 127.0.0.1 and check that it gets its cookie.
                openIframe(thirdPartyBaseUrl + subPathToGetCookies + "&message=Should receive one cookie.", finishTest);
                break;
        }
    }

    if (document.location.host === partitionHost && document.location.hash == "" && window.testRunner && window.internals) {
        testRunner.waitUntilDone();
        testRunner.dumpChildFramesAsText();
        setEnableFeature(true, function() {
            testRunner.setStatisticsPrevalentResource(thirdPartyOrigin, false, function() {
                testRunner.setStatisticsHasHadUserInteraction(thirdPartyOrigin, false, function() {
                    document.location.hash = "step1";
                    testRunner.statisticsUpdateCookieBlocking(runTest);
                });
            });
        });
    } else {
        runTest();
    }
</script>
</body>
</html>
