<?php

function getid(): string {
    return str_pad(bin2hex(random_bytes(16)), 32, "0", STR_PAD_LEFT);
}

function delTree($dir) { 
    foreach (scandir($dir) as $ent) {
        if ($ent === "." || $ent === "..")
            continue;
        $path = $dir . DIRECTORY_SEPARATOR . $ent;
        if (is_dir($path))
            delTree($path);
        else
            unlink($path);
    }
    return rmdir($dir);
}

$defaultCode = <<<java
public class Program {
    public static void main(String[] args) {
        // Your code here
        System.out.println("Hello, world!");
    }
}
java;

$code = null;
$result = null;

if (isset($_POST["code"]) && strlen($_POST["code"]) <= 16383) {
    $id = getid();

    $code = $_POST["code"];

    $srcDir = __DIR__ . "/../_runners/$id/src";

    mkdir($srcDir, recursive: true);

    file_put_contents($srcDir . "/Program.java", $code);

    chdir(__DIR__ . "/..");
    $resultStr = shell_exec("./compile-and-run.sh '$id' Program 2>/dev/null");
    chdir(__DIR__);

    if (is_string($resultStr)) {
        $result = json_decode($resultStr, true);
    }

    header("Content-Type: application/json");
    echo json_encode($result);
    exit;
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=916, initial-scale=1.0">
    <title>Java</title>
    <link rel="stylesheet" href="codemirror.css">
    <link rel="stylesheet" href="eclipse.css">
    <link rel="stylesheet" href="site.css">
    <script src="jquery-1.12.4.min.js"></script>
    <script src="codemirror.js"></script>
    <script src="clike.js"></script>
</head>
<body>
    <div id="loader" style="display: none;">
        <div id="spinner"></div>
    </div>
    <h1>&#9749;&#65039; Java Compiler</h1>
    <p>Powered by Eclipse Temurin</p>
    <form method="POST">
        <textarea maxlength="16383" id="editor" name="code" rows="20"><?= htmlentities($code ?? $defaultCode) ?></textarea>
        <br>
        <button type="submit">&#9654;&nbsp;Compile &amp; run</button>
    </form>
    <div id="output" style="display: none;">
        
    </div>

    <script>
        $(function() {
            var editor = CodeMirror.fromTextArea($("#editor")[0], {
                lineNumbers: true,
                mode: "text/x-java",
                theme: "eclipse",
                tabSize: 4,
                indentWithTabs: false,
                smartIndent: true,
                indentUnit: 4
            });
            editor.setSize(900, 500);

            $("form").on("submit", function(e) {
                e.preventDefault();

                $("#loader").show();
                $("#output").empty().hide();

                $.ajax({
                    type: "POST",
                    url: location.href,
                    data: {
                        code: editor.getValue()
                    },
                    dataType: "json",
                    success: function(data) {
                        $("#loader").hide();

                        if (data.compile.status == 0) {
                            if (data.run.status != null) {
                                // program was executed
                                $("#output").append(
                                    $("<h4></h4>").text(data.run.status == 0 ? "Executed successfully" : "Execution failed").css("color", data.run.status == 0 ? "green" : "red"),
                                );

                                if (data.run.stdout) {
                                    $("#output").append(
                                        $("<p></p>").text("Program output:"),
                                        $("<pre></pre>").append(
                                            $("<code></code>").text(data.run.stdout)
                                        )
                                    );
                                }

                                if (data.run.stderr) {
                                    $("#output").append(
                                        $("<p></p>").text("Error output:"),
                                        $("<pre></pre>").append(
                                            $("<code></code>").text(data.run.stderr)
                                        )
                                    );
                                }
                            }
                        } else {
                            // compilation failed, stderr will contain compiler errors
                            $("#output").append(
                                $("<h4></h4>").text("Compilation failed").css("color", "red"),
                                $("<p></p>").text("Compiler errors:"),
                                $("<pre></pre>").append(
                                    $("<code></code>").text(data.compile.stderr)
                                )
                            );
                        }

                        $("#output").slideDown(400);
                    }
                })
            });
        });
    </script>
</body>
</html>