<!DOCTYPE html>
<html>
<head>
    <title>MtG Card Data Collector</title>
    <style>
        * {
            box-sizing: border-box;

            font-family: sans-serif;
            font-size: 12pt;
        }
        h1 {
            font-size: 2rem;
            border-bottom: 0.1em solid lightgray;
            display: inline-block;
        }

        footer {
            display: inline-block;
            border-top: 0.2em solid lightgray;
        }
        footer,
        footer * {
            font-size: 0.75rem;
        }

        table#result {
            border-collapse: collapse;
        }

        table#result td {
            border: 1px solid gray;
            padding: 0.5em;
        }

        div.table {
            display: table;
            max-width: 800px;
            width: 100%;
            border: 1px solid lightgray;
            margin: 1em 0;
        }

        div.table>div.row {
            display: table-row;
            margin-right: 0.5em;
        }
        div.table>div:nth-child(2n+1) {
            background-color: #eeeeee;
        }

        div.table>div.row>* {
            display: table-cell;
            margin-top: 0.5em;
            margin-bottom: 0.5em;

        }
        div.table>div.row>:first-child {
            vertical-align: top;
            padding: 0.5em;
            padding-right: 1em;
            width: 200px;
            font-weight: bold;
        }
        div.table div.row>:not(:first-child) {
            width: 100%;
            margin-right: 0.5em;
        }

        label small {
            font-size: 0.75em;
            font-weight: normal;
        }
        textarea#query {
            font-family: monospace;
        }
        button[type=submit] {
            border: 0.25em solid hsl(224, 78%, 90%);
            border-radius: 0.5em;
            padding: 0.5em 0.8em;
            background-color: hsl(224, 78%, 75%);
            font-weight: bold;
        }
        button[type=submit]:hover {
            border-color: hsl(224, 78%, 75%);
            background-color: hsl(224, 78%, 90%);
        }
        button[type=submit]:disabled {
            border-color: hsl(224, 20%, 90%);
            background-color: hsl(224, 20%, 75%);
        }

        :required:invalid, :focus:invalid {
            background-color: #ffeeee;
        }
    </style>
    <script type="text/javascript">
        function updateLineCounter() {
            var linecounter = document.getElementById("linecounter");
            var submit = document.getElementById("submit");
            var queryfield = document.getElementById("query");

            var count = query.value.split(/\r|\r\n|\n/).length;
            linecounter.textContent = count+"/100";

            if (count > 100) {
                linecounter.setAttribute("style", "color: red;");
                submit.setAttribute("disabled", "disabled");
            } else {
                linecounter.removeAttribute("style");
                submit.removeAttribute("disabled");
            }
        }
    </script>
</head>
<body>
    <header>
        <h1>MtG Card Data Collector</h1>
    </header>
    <main>
<?php

require 'vendor/autoload.php';

//$context = stream_context_create(['wrapper' => [
//    'user_agent' => '',
//    'protocol_version' => 1.1
//]]);


function get_card_data($url) {
    $fp = fopen($url, 'r');
    $meta = stream_get_meta_data($fp);
    $content = stream_get_contents($fp);
    fclose($fp);

    $headers = [];
    foreach ($meta["wrapper_data"] as $line) {
        $parts = explode(":", $line, 2);
        if (isset($parts[1]))
            $headers[trim($parts[0])] = trim($parts[1]);
    }

    return ["meta" => $meta, "header" => $headers, "data" => json_decode($content, true)['cards'][0]];
}

function x() {
    $engine = new StringTemplate\Engine;

    if (isset($_REQUEST['query'])) {
        $q = $_REQUEST['query'];
        if (strlen($q) < 3){
            echo "<p style='font-size: 1.5em; margin: 2em 1em;'>(屮゚Д゚)屮</p>";
            return;
        }

        switch ($_REQUEST['format']) {
            case "cardname":
                $template = "{name}";
                break;
            case "set:number":
                $template = "{set}: {number}";
                break;
            case "setname:cardname":
            default:
                $template = "{setName}: {name}";
        }

        $lines = explode("\n", $q);
        if (count($lines) > 100) {
            echo "<p>Please request no more than 100 cards at a time</p>";
            return;
        }

        echo '<pre style="font-family: monospace; background-color: lightgray; border-radius: 5px; padding: 3px 6px;">';
        if (!empty($_REQUEST["prefix"]))
            echo '<table id=result><tbody>';

        $urls_only = false;
        foreach ($lines as $i => $line) {
            $parts = explode(' ', trim($line));
            if (count($parts) !== 2)
                continue;

            $url = "https://api.magicthegathering.io/v1/cards?set=$parts[0]&number=$parts[1]";

            if (!$urls_only) {
                $response = get_card_data($url);
                if (isset($response["header"]["Ratelimit-Remaining"]) and $response["header"]["Ratelimit-Remaining"] === "0") {
                    echo "<br>Rate limit exceeded. Please try again in a few hours or use the raw result URLs.<br><br>";
                    $urls_only = true;
                }
            }

            if (!empty($_REQUEST["prefix"]))
                echo "<tr><td><a href=\"$url\">$parts[0] $parts[1]</a></td><td>";
            elseif ($urls_only)
                echo "$parts[0] $parts[1]: ";

            if (empty($response["data"]))
                echo "Card not found :(";
            elseif (!$urls_only)
                echo $engine->render($template, $response["data"]);
            else
                echo "<a href=\"$url\">$url</a>";

            if (!empty($_REQUEST["prefix"]))
                echo '</td></tr>';
            else
                echo "\n";
        }
        if (!empty($_REQUEST["prefix"]))
            echo '</tbody></table>';
        echo '</pre><hr>';
    }
}
x()
?>
        <form id=form method=post>
            <div class="table">
                <div class="row">
                    <label for="format">Output Format:</label>
                    <div>
                        <select type="text" id="format" name="format" required>
<?php
foreach ([
    "Card name" => "cardname",
    "Set name: Card name" => "setname:cardname",
    "Set: Number" => "set:number",
] as $label => $value) {
    $selected = $_REQUEST["format"] === $value ? " selected" : "";
    echo "<option value=\"$value\" $selected>$label</option>";
}
?>
                        </select>
                        <label style="display: block; margin: 0.25em 0;">
                            <input name=prefix value=1 type=checkbox <?= !empty($_REQUEST["prefix"]) ? "checked" : "" ?>>
                            Prefix with input and raw result URL
                        </label>
                    </div>
                </div>
                <div class="row">
                    <label for="query">Cards:<br><small id=linecounter>0/100</small></label>
                    <textarea id="query" name="query" rows="20" onkeyup="updateLineCounter();" <?= !isset($_REQUEST['query']) ? "autofocus" : "" ?> required placeholder="M12 7
ORI 25
AER 178"><?= !empty($_REQUEST['query']) ? $_REQUEST['query'] : "" ?></textarea>
                </div>
                <div class="row">
                    <div></div>
                    <div>
                        <p>
                            Please keep in mind the data source for this service enforces a daily request limit,
                            so please don't waste it. If no cards are found and you are sure your set codes and
                            card numbers are valid, try again in a few hours or use the raw result URLs.
                        </p>
                        <p>
                            Depending on how many cards you entered, loading the data will take a while.
                        </p>
                    </div>
                </div>
                <div class="row">
                    <span></span>
                    <button id=submit type="submit">Submit</button>
                </div>
            </div>
        </form>
    </main>
    <footer>
        <p>
            Version:
<?php
    $stdout=[];
    exec("git log --format=\"%h|%cd|%d\" --decorate=short --date=short HEAD~1..HEAD", $stdout);
    $parts = explode("|", $stdout[0]);

    $offset_start = strpos($parts[2], "tag: ");
    if ($offset_start !== false) {
        $offset_start += 5;
        $offset_end = strpos($parts[2], ",", $offset_start) or strpos($parts[1], ")", $offset_start);

        echo substr($parts[2], $offset_start, $offset_end - $offset_start), "; ";
    }
    echo $parts[0], " (", $parts[1], ")";
?>
            | <a href="https://git.zom.bi/fanir/mtg-cdc">Source</a>
        </p>
    </footer>
    <script type="text/javascript">updateLineCounter()</script>
</body>
</html>