<!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>
<script>
    description("Test for partitioned and unpartitioned cookie deletion.");
    jsTestIsAsync = true;

    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 subPathToSetFirstPartyCookieRandom = "/set-cookie.py?name=" + firstPartyCookieName + "&value=value&dummyParam=" + Math.random();
    const thirdPartyCookieName = "thirdPartyCookie";
    const subPathToSetThirdPartyCookie = "/set-cookie.py?name=" + thirdPartyCookieName + "&value=value";
    const fragmentWithReturnUrl = "http://" + partitionHost + "/resourceLoadStatistics/cookie-deletion.html";
    const subPathToGetCookies = "/get-cookies.py?name1=" + firstPartyCookieName + "&name2=" + thirdPartyCookieName;

    function finishTest() {
        console.log("in finishTest")
        setEnableFeature(false, finishJSTest);
    }

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


    function fireDataModificationHandlerAndContinue() {
        console.log("In fireDataModificationHandlerAndContinue")
        testRunner.installStatisticsDidScanDataRecordsCallback(function() {
            console.log("In callback function for installStatisticsDidScanDataRecordsCallback")
            setTimeout(runTest, 500);
        });
        console.log("Calling statisticsProcessStatisticsAndDataRecords")
        testRunner.statisticsProcessStatisticsAndDataRecords();
    }

    function setAsNonPrevalentAndContinue() {
        console.log("In setAsNonPrevalentAndContinue")
        testRunner.setStatisticsPrevalentResource(thirdPartyOrigin, false, function() {
            console.log("In callback function for setStatisticsPrevalentResource")
            if (testRunner.isStatisticsPrevalentResource(thirdPartyOrigin))
                testFailed("Host still set as prevalent resource.");
            testRunner.statisticsUpdateCookieBlocking(runTest);
        });
    }

    function runTest() {
        switch (document.location.hash) {
            case "#step1":
                console.log("step1. About to set a cookie")
                // Set first-party cookie for localhost.
                document.location.href = thirdPartyBaseUrl + subPathToSetFirstPartyCookieRandom + "#" + fragmentWithReturnUrl + "#step2";
                break;
            case "#step2":
                console.log("step2. About to open an iFrame to test for third party cookie access (should be successful)")
                // Check that the third-party has access to its first-party cookies.
                document.location.hash = "step3";
                openIframe(thirdPartyBaseUrl + subPathToGetCookies + "&message=Should receive first-party cookie.", runTest);
                break;
            case "#step3":
                console.log("step3. About to classify localhost as prevalent")
                // Classify localhost as prevalent.
                document.location.hash = "step4";
                testRunner.setStatisticsPrevalentResource(thirdPartyOrigin, true, function() {
                    console.log("step3. In the callback for testRunner.setStatisticsPrevalentResource")
                    if (!testRunner.isStatisticsPrevalentResource(thirdPartyOrigin))
                        testFailed("Host did not get set as prevalent resource.");
                    testRunner.statisticsUpdateCookieBlocking(runTest);
                });
                break;
            case "#step4":
                console.log("step4. About to open an iFrame to test for third party cookie access (should not be successful)")
                // Check that the third-party no longer has access to its first-party cookies.
                document.location.hash = "step5";
                openIframe(thirdPartyBaseUrl + subPathToGetCookies + "&message=Should receive no cookies.", runTest);
                break;
            case "#step5":
                console.log("step5. About to open an iFrame to try to set a cookie as a third party (should fail)")
                // Try setting a cookie as third-party.
                document.location.hash = "step6";
                openIframe(thirdPartyBaseUrl + subPathToSetThirdPartyCookie + "&message=Try to set third party cookie.", runTest);
                break;
            case "#step6":
                console.log("step6. About to open an iFrame and fireDataModificationHandlerAndContinue")
                // Check that the third-party still has no access to cookies and then fire data record removal.
                document.location.hash = "step7";
                openIframe(thirdPartyBaseUrl + subPathToGetCookies + "&message=Should receive no cookies.", fireDataModificationHandlerAndContinue);
                break;
            case "#step7":
                console.log("step7. About to open an iFrame and setAsNonPrevalentAndContinue")
                // Check that the third-party still has no access to cookies and then declassify localhost.
                document.location.hash = "step8";
                openIframe(thirdPartyBaseUrl + subPathToGetCookies + "&message=After removal, should receive no cookies.", setAsNonPrevalentAndContinue);
                break;
            case "#step8":
                console.log("step8. About to open an iFrame and confirm third party has no cookie access")
                // Check that the third-party still has no access to cookies.
                openIframe(thirdPartyBaseUrl + subPathToGetCookies + "&message=After declassified, should receive no cookies.", finishTest);
                break;
        }
    }

    if (document.location.host === partitionHost && document.location.hash === "" && window.testRunner && window.internals) {
        setEnableFeature(true, function() {
            console.log("Test is beginning. document.location.hash is empty.")
            testRunner.setStatisticsShouldClassifyResourcesBeforeDataRecordsRemoval(false);
            testRunner.setStatisticsMinimumTimeBetweenDataRecordsRemoval(0);

            testRunner.dumpChildFramesAsText();
            document.location.hash = "step1";
            console.log("About to call runTest() for the first time.")
            runTest();
        });
    } else {
        console.log("About to call runTest() after cookie was set. document hash is " + document.location.hash)
        runTest();
    }

</script>
</body>
</html>
