<?php

function GetMoves() {
    $input = fopen(realpath("./Game/") . "/NextActions", 'r') or die("can't open file");
    $line = fgets($input);
    $output = fopen(realpath("./Game/") . "/ActionFork", 'w') or die("can't open file");
    $_SESSION["action_count"] = 0;
    while ($line != FALSE) {
        $i = strpos($line, ":");
        if ($i != FALSE) {
            if (strpos($line, "STATE 0:") === 0) {
                $line[strlen($line) - 1] = ",";
                $line[strlen($line)] = "\n";
                fwrite($output, $line);
            }
            if (strpos($line, "ACTIONS:") === 0) {
                $action = str_getcsv($line, " ");
                $_SESSION["action_" . $_SESSION["action_count"] . ""] = $action[1];
                $_SESSION["action_count"]++;
                fwrite($output, $line);
            }
            if (strpos($line, "STATE 1:") === 0) {
                $line[strlen($line) - 1] = ",";
                $line[strlen($line)] = "\n";
                fwrite($output, $line);
            }
        }
        $line = fgets($input);
    }
    fclose($input);
    fclose($output);
}

function ActionChoice() {
    echo "<table id= \"actionchoice\"><tr>";
    echo "<form action=\"engine.php\" method=\"post\">";
    $val = 1;
    $_SESSION["print"] = TRUE;
    $_SESSION["sel_action"] = FALSE;
    for ($i = 0; $i < $_SESSION["action_count"]; $i++) {
        if ($_SESSION["action_$i"] != "(no") {
            if($i % 4 == 0){
                echo "</tr><tr>";
            }
            echo "<td class=\"mid\">";
            echo '<input type="submit" name="sel_action" label="action' . $i . '" value="' . $val++ . '.' . $_SESSION["action_$i"] . '"/>';
            echo "</td>";
            if (isset($_SESSION["engine_processing"])) {
                if (($_SESSION["engine_processing"] === TRUE) && ($_SESSION["action_$i"] === "engine_next_step")) {
                    $_SESSION["sel_action"] = TRUE;
                    $_SESSION["print"] = FALSE;
                    endScript("engine.php");
                }
                if (($_SESSION["engine_processing"] === TRUE) && ($_SESSION["action_$i"] === "system_next_move")) {
                    $_SESSION["sel_action"] = TRUE;
                    $_SESSION["print"] = FALSE;
                    endScript("engine.php");
                }
            }
        } else {
            $val++;
        }
    }
    echo "</tr>\n<tr>";
    echo "</tr>\n";
    echo "</form>";
    echo "<tr><form action=\"options.php\" method=\"post\">";
    echo '<td class=\"mid\"><input type="submit" name="snapshot" label="action1" value="1"/>load last action</td>';
    echo '<td class=\"mid\"><input type="submit" name="snapshot" label="action2" value="2"/>load saved game</td>';
    echo '<td class=\"mid\"><input type="submit" name="snapshot" label="action3" value="3"/>save game</td>';
    echo "</form></tr>\n</table>";
}

function UpdateInitally() {
    if (isset($_SESSION["sel_action"])) {
        if ($_SESSION["sel_action"] === TRUE) {
            $returnedValue = 1;
        } else {
            $returnedValue = $_POST["sel_action"];
        }
    }
    if(isset($_SESSION["dumo"])){
        $returnedValue = $_SESSION["dumo"];
        unset($_SESSION["dumo"]);
    }
    $second_snapshotfile = fopen(realpath("./Game/") . "/LastState", 'w');
    $snapshot_file = fopen(realpath("./Game/") . "/CurrentState", 'r');
    $str = fgets($snapshot_file);
    while ($str != FALSE) {
        fwrite($second_snapshotfile, $str);
        $str = fgets($snapshot_file);
    }
    fclose($snapshot_file);
    fclose($second_snapshotfile);
    $selval = (($returnedValue) * 3) - 1; // -1 cause the numbering is from 0. *3 cause its 3 lines per action
    $actions_file = fopen(realpath("./Game/") . "/ActionFork", 'r');
    for ($i = 0; $i < $selval; $i++) {
        $str = fgets($actions_file);
    }
    $str = fgets($actions_file);
    $initially_file = fopen(realpath("./Game/") . "/initially", 'w');
    $snapshot_file = fopen(realpath("./Game/") . "/CurrentState", 'w');
    fputs($initially_file, "\ninitially:\n");
    //the last "," is transformed
    $str = str_replace(",\n", ".", $str);
    //the state expression is deleted
    $str = str_replace("STATE 1: ", "   ", $str);
    //fluents are transformed into facts
    $str = str_replace("),", ").", $str);
    //some fluents don't have arguments, but need to be transformed
    $str = str_replace(", ", ".", $str);
    //now comes just formating the code
    $str = str_replace(". ", ".", $str);
    $str = str_replace(".", ".\n   ", $str);
    fwrite($initially_file, $str . "\n");
    fwrite($snapshot_file, $str . "\n");
    fclose($initially_file);
    fclose($snapshot_file);
    fclose($actions_file);
}

function GeneratePlayersDl() {
    $file = fopen(realpath("./Dlv/") . "/players.dl", "w") or die("can't open file");
    ;
    fputs($file, "%players\n\n");
    for ($i = 0; $i < $_POST["players"]; $i++) {
        fputs($file, "player(p" . $i . ").\n");
    }
    for ($i = 0; $i < $_POST["players"]; $i++) {
        if ($i != $_POST["players"] - 1)
            fputs($file, "next_player(p" . $i . ",p" . ($i + 1) . ").\n");
        else
            fputs($file, "next_player(p" . $i . ",p0).\n");
    }
    fclose($file);
}

function GenerateStart() {
    copy(realpath("./Game/Core/") . "/core.dl", realpath("./Game/") . "/TheGame.dl");
    $w_file = fopen(realpath("./Game/") . "/initially", 'w');
    $r_file = fopen(realpath("./Dlv/") . "/deck.plan", 'r');
    $str = fgets($r_file);
    while ($str != FALSE) {
        fputs($w_file, $str);
        $str = fgets($r_file);
    }
    fclose($r_file);
    $r_file = fopen(realpath("./Dlv/") . "/initially.plan", 'r');
    $str = fgets($r_file);
    $str = fgets($r_file);
    while ($str != FALSE) {
        fputs($w_file, $str);
        $str = fgets($r_file);
    }
    transferCoreCode();
}

function transferCoreCode() {
    unlink(realpath("./Game/") . "/fluents");
    unlink(realpath("./Game/") . "/TheGame.dl");
    unlink(realpath("./Game/") . "/actions");
    unlink(realpath("./Game/") . "/always");
    unlink(realpath("./Game/") . "/goal");
    copy(realpath("./Game/Core/") . "/fluents", realpath("./Game/") . "/fluents");
    copy(realpath("./Game/Core/") . "/actions", realpath("./Game/") . "/actions");
    copy(realpath("./Game/Core/") . "/always", realpath("./Game/") . "/always");
    copy(realpath("./Game/Core/") . "/goal", realpath("./Game/") . "/goal");
    copy(realpath("./Game/Core/") . "/core.dl", realpath("./Game/") . "/TheGame.dl");
}

function saveModules($str){
    if($_SESSION["modules"]["static_abilities"] == TRUE){
        fputs($handle, "static_abilities\n");
    }
    if($_SESSION["modules"]["abilities"] == TRUE){
        fputs($handle, "abilities\n");
    }
    if($_SESSION["modules"]["triggered_abilities"] == TRUE){
        fputs($handle, "triggered_abilities\n");
    }
    if($_SESSION["modules"]["resolve_process"] == TRUE){
        fputs($handle, "resolve_process\n");
    }
    if($_SESSION["modules"]["casting_process"] == TRUE){
        fputs($handle, "casting_process\n");
    }
    if($_SESSION["modules"]["combat_phase"] == TRUE){
        fputs($handle, "combat_phase\n");
    }
    if($_SESSION["modules"]["drawing_cards"] == TRUE){
        fputs($handle, "drawing_cards\n");
    }
}

function PrintModules(){
    if($_SESSION["modules"]["static_abilities"] == TRUE){
        echo "<p>static_abilities</p>";
    }
    if($_SESSION["modules"]["abilities"] == TRUE){
        echo "<p>abilities</p>";
    }
    if($_SESSION["modules"]["triggered_abilities"] == TRUE){
        echo "<p>triggered_abilities</p>";
    }
    if($_SESSION["modules"]["resolve_process"] == TRUE){
        echo "<p>resolve_process</p>";
    }
    if($_SESSION["modules"]["casting_process"] == TRUE){
        echo "<p>casting_process</p>";
    }
    if($_SESSION["modules"]["combat_phase"] == TRUE){
        echo "<p>combat_phase</p>";
    }
    if($_SESSION["modules"]["drawing_cards"] == TRUE){
        echo "<p>drawing_cards</p>";
    }
}

function setModules() {
    $_SESSION["modules"]["static_abilities"] = FALSE;
    $_SESSION["modules"]["abilities"] = FALSE;
    $_SESSION["modules"]["triggered_abilities"] = FALSE;
    $_SESSION["modules"]["resolve_process"] = FALSE;
    $_SESSION["modules"]["casting_process"] = FALSE;
    $_SESSION["modules"]["combat_phase"] = FALSE;
    $_SESSION["modules"]["drawing_cards"] = FALSE;
}

function UpdateGameplan() {
    $game_plan = fopen(realpath("./Game/") . "/TheGame.plan", 'w') or die("can't open file");
    $r_file = fopen(realpath("./Game/") . "/fluents", 'r') or die("can't open file");
    fwrite($game_plan, fread($r_file, filesize(realpath("./Game/") . "/fluents")));
    fclose($r_file);
    $r_file = fopen(realpath("./Game/") . "/actions", 'r') or die("can't open file");
    fwrite($game_plan, fread($r_file, filesize(realpath("./Game/") . "/actions")));
    fclose($r_file);
    $r_file = fopen(realpath("./Game/") . "/always", 'r') or die("can't open file");
    fwrite($game_plan, fread($r_file, filesize(realpath("./Game") . "/always")));
    fclose($r_file);
    $r_file = fopen(realpath("./Game/") . "/initially", 'r') or die("can't open file");
    fwrite($game_plan, fread($r_file, filesize(realpath("./Game/") . "/initially")));
    fclose($r_file);
    $r_file = fopen(realpath("./Game/") . "/goal", 'r') or die("can't open file");
    fwrite($game_plan, fread($r_file, filesize(realpath("./Game/") . "/goal")));
    fclose($r_file);
}

function GenerateNextPossibleActions($last_object) {
    $file = fopen(realpath("./Game/") . "/NextActions", "w") or die("can't open file");
    //windows
    $str = shell_exec(".\Dlv\dlv.mingw.exe ". realpath("./Game/") . "/TheGame.dl  " . realpath("./Game/") . "/TheGame.plan -FPopt -N=$last_object -planlength=1");
    //linux
    //$str = shell_exec(realpath("./Dlv/dlv.i386-linux-elf-static.bin") . " " . realpath("./Game/TheGame.dl") . " " . realpath("./Game/TheGame.plan") . " -FPopt -N=$last_object -planlength=1");
    $str = str_replace("$", "%", $str);
    fputs($file, $str);
    fclose($file);
}

function Parser($input) {
    $ws_pos = str_getcsv($input, " ");
    $output = fopen(realpath("./Game/") . "/fluents", "w") or die("can't open file");
    fwrite($output, "fluents:\n");
    fclose($output);
    $output = fopen(realpath("./Game/") . "/actions", "w") or die("can't open file");
    fwrite($output, "actions:\n");
    fclose($output);
    $output = fopen(realpath("./Game/") . "/always", "w") or die("can't open file");
    fwrite($output, "always:\n");
    fclose($output);
    $output = fopen(realpath("./Game/") . "/initially", "w") or die("can't open file");
    fwrite($output, "initially:\n");
    fclose($output);
    $output = fopen(realpath("./Game/") . "/goal", "w") or die("can't open file");
    fwrite($output, "goal:\n");
    for ($i = 0; $i < count($ws_pos); $i++) {
        if (file_exists(realpath($ws_pos[$i]))) {
            $r_file = fopen(realpath($ws_pos[$i]), 'r') or die("can't open file");
            $str = fgets($r_file);
            while ($str != FALSE) {
                switch (trim($str)) {
                    case "fluents:": {
                            fclose($output);
                            $output = fopen(realpath("./Game/") . "/fluents", 'a') or die("can't open file");
                            break;
                        }
                    case "actions:": {
                            fclose($output);
                            $output = fopen(realpath("./Game/") . "/actions", 'a') or die("can't open file");
                            break;
                        }
                    case "always:": {
                            fclose($output);
                            $output = fopen(realpath("./Game/") . "/always", 'a') or die("can't open file");
                            break;
                        }
                    case "initially:": {
                            fclose($output);
                            $output = fopen(realpath("./Game/") . "/initially", 'a') or die("can't open file");
                            break;
                        }
                    case "goal:": {
                            fclose($output);
                            $output = fopen(realpath("./Game/") . "/goal", 'a') or die("can't open file");
                            break;
                        }
                    default: {
                            fwrite($output, $str);
                            break;
                        }
                }
                $str = fgets($r_file);
            }
        }
    }
    UpdateGameplan();
    fclose($output);
    fclose($r_file);
}

function abilityParser($ability) {
    $start = strpos($ability, "{");
    $end = strpos($ability, "}");
    $abcostArray = array();
    while ($end != FALSE) {
        $abcost = substr($ability, $start + 1, $end - 1);
        $abcostArray[count($abcostArray)] = $abcost;
        $ability = substr($ability, $end);
        $start = strpos($ability, "{");
        $end = strpos($ability, "}");
    }
    $end = strpos($ability, ":") + 1;
    $abcostArray[count($abcostArray)] = substr($ability, $end);
    return $abcostArray;
}

function constructDeck($DB_adress, $DB_name, $U_name, $U_password) {
    $new_deck = new InputParser();
    $new_deck->setDatabaseAdress($DB_adress);
    $new_deck->setDatabaseName($DB_name);
    $new_deck->setUserName($U_name);
    $new_deck->setUserPassword($U_password);
    $new_deck->resetLastObject();

    $new_deck->setOwner("p0");
    $new_deck->setInputfileName(realpath("./Game/deck1.list"));
    $new_deck->constructDeck();
    $objectsInDeck1 = $new_deck->getLastObject();
    $new_shuffler = new deckShuffler(1, $objectsInDeck1, realpath("./Game/deckshuffle1.dl"), "p0");

    $new_deck->setOwner("p1");
    $new_deck->setInputfileName(realpath("./Game/deck2.list"));
    $new_deck->constructDeck();
    $new_shuffler = new deckShuffler($objectsInDeck1, $new_deck->getLastObject(), realpath("./Game/deckshuffle2.dl"), "p1");
}

function DumpInitiallyIntoFile($gameHandler) {
    $initially_file = fopen(realpath("./Game/") . "/initially", 'w');
    fputs($initially_file, "\ninitially: \n");
    for ($i = 0; $i < $gameHandler->fluentArraySize(); $i++) {
        fputs($initially_file, $gameHandler->getFluentArray($i)->getName());
        if ($gameHandler->getFluentArray($i)->parameterArraySize() <> 0) {
            fputs($initially_file, "(");
            $paramArraySize = $gameHandler->getFluentArray($i)->parameterArraySize();
            for ($j = 0; $j < $paramArraySize; $j++) {
                fputs($initially_file, $gameHandler->getFluentArray($i)->getParameterArray($j));
                if ($j < $paramArraySize - 1) {
                    fputs($initially_file, ",");
                }
            }
            fputs($initially_file, ")");
        }
        fputs($initially_file, ".\n");
        unset($paramArraySize);
    }
}

function MakeFirstInitially() {
    $r_file = fopen(realpath("./Game/") . "/deckshuffle1.dl", 'r') or die("can't open file");
    $w_file = fopen(realpath("./Dlv/") . "/deck.plan", 'w') or die("can't open file");
    fwrite($w_file, "initially: \n");
    $str = fgets($r_file);
    while ($str != FALSE) {
        fputs($w_file, $str);
        $str = fgets($r_file);
    }
    fclose($r_file);
    $r_file = fopen(realpath("./Game/") . "/deckshuffle2.dl", 'r') or die("can't open file");
    $str = fgets($r_file);
    while ($str != FALSE) {
        fputs($w_file, $str);
        $str = fgets($r_file);
    }
    fclose($r_file);
}

function PrepareModules() {
    //treba si predpripravit z kazdeho suboru always co obsahuje.
    $source_file = fopen(realpath("./Game/") . "/plan.list", "r") or die("can't open file");
    $str = fgets($source_file);
    $str = trim($str);
    $command_line = "";
    while ($str != FALSE) {
        if (file_exists($str)) {
            $command_line = $command_line . " " . $str;
            $str = fgets($source_file);
            $str = trim($str);
        } else {
            $str = fgets($source_file);
            $str = trim($str);
        }
    }
    fclose($source_file);
    $output = fopen(realpath("./Game/Core/") . "/fluents", 'a') or die("can't open file");
    //parse the logic part
    $ws_pos = str_getcsv($command_line, " ");
    for ($i = 0; $i < count($ws_pos); $i++) {
        if (file_exists($ws_pos[$i])) {
            $r_file = fopen($ws_pos[$i], 'r') or die("can't open file");
            $str = fgets($r_file);
            $end = false;
            while (($str != FALSE) && ($end === FALSE)) {
                switch (trim($str)) {
                    case "fluents:": {
                            fclose($output);
                            $output = fopen(realpath("./Game/Modules/") . "/dummyfile", 'w') or die("can't open file");
                            break;
                        }
                    case "actions:": {
                            fclose($output);
                            $output = fopen(realpath("./Game/Modules/") . "/dummyfile", 'w') or die("can't open file");
                            break;
                        }
                    case "always:": {
                            $index = strrpos($ws_pos[$i], "/");
                            $output = fopen(realpath("./Game/Modules/") . "/" . substr($ws_pos[$i], $index + 1), 'w') or die("can't open file");
                            break;
                        }
                    case "initially:": {
                            $end = TRUE;
                            break;
                        }
                    case "goal:": {
                            $end = TRUE;
                            break;
                        }
                    default: {
                            fwrite($output, $str);
                            break;
                        }
                }
                $str = fgets($r_file);
            }
        }
    }
}

function PrepareCore() {
    $source_file = fopen(realpath("./Game/Core/") . "/core_plan.list", "r") or die("can't open file");
    $str = fgets($source_file);
    $str = trim($str);
    $command_line = "";
    while ($str != FALSE) {
        if (file_exists($str)) {
            $command_line = $command_line . " " . $str;
            $str = fgets($source_file);
            $str = trim($str);
        } else {
            $str = fgets($source_file);
            $str = trim($str);
        }
    }
    fclose($source_file);
    //Prepare background knowledge 
    $w_file = fopen(realpath("./Game/Core/") . "/core.dl", 'w') or die("can't open file");
    $source_file = fopen(realpath("./Game/Core/") . "/core_dl.list", "r") or die("can't open file");
    $str = fgets($source_file);
    $str = trim($str);
    $r_file;
    while ($str != FALSE) {
        if (file_exists($str)) {
            $r_file = fopen($str, 'r') or die("can't open file");
            fputs($w_file, fread($r_file, filesize($str)));
            $str = fgets($source_file);
            $str = trim($str);
        } else {
            $str = fgets($source_file);
            $str = trim($str);
        }
    }
    //parse the logic part
    $ws_pos = str_getcsv($command_line, " ");
    $output = fopen(realpath("./Game/Core/") . "/fluents", "w") or die("can't open file");
    fwrite($output, "fluents:\n");
    fclose($output);
    $output = fopen(realpath("./Game/Core/") . "/actions", "w") or die("can't open file");
    fwrite($output, "actions:\n");
    fclose($output);
    $output = fopen(realpath("./Game/Core/") . "/always", "w") or die("can't open file");
    fwrite($output, "always:\n");
    fclose($output);
    $output = fopen(realpath("./Game/Core/") . "/initially", "w") or die("can't open file");
    fwrite($output, "initially:\n");
    fclose($output);
    $output = fopen(realpath("./Game/Core/") . "/goal", "w") or die("can't open file");
    fwrite($output, "goal:\n");
    for ($i = 0; $i < count($ws_pos); $i++) {
        if (file_exists($ws_pos[$i])) {
            $r_file = fopen($ws_pos[$i], 'r') or die("can't open file");
            $str = fgets($r_file);
            while ($str != FALSE) {
                switch (trim($str)) {
                    case "fluents:": {
                            fclose($output);
                            $output = fopen(realpath("./Game/Core/") . "/fluents", 'a') or die("can't open file");
                            break;
                        }
                    case "actions:": {
                            fclose($output);
                            $output = fopen(realpath("./Game/Core/") . "/actions", 'a') or die("can't open file");
                            break;
                        }
                    case "always:": {
                            fclose($output);
                            $output = fopen(realpath("./Game/Core/") . "/always", 'a') or die("can't open file");
                            break;
                        }
                    case "initially:": {
                            fclose($output);
                            $output = fopen(realpath("./Game/Core/") . "/initially", 'a') or die("can't open file");
                            break;
                        }
                    case "goal:": {
                            fclose($output);
                            $output = fopen(realpath("./Game/Core/") . "/goal", 'a') or die("can't open file");
                            break;
                        }
                    default: {
                            fwrite($output, $str);
                            break;
                        }
                }
                $str = fgets($r_file);
            }
        }
    }
    fclose($output);
    fclose($r_file);
}

function endScript($url) {
    $numb = rand(1,1000);
    header("Location:" . $url . "?id = " . $numb);
    exit();
}

function CoreFluents() {
    $source_file = fopen(realpath("./Game/") . "/plan.list", "r") or die("can't open file");
    $str = fgets($source_file);
    $str = trim($str);
    $command_line = "";
    while ($str != FALSE) {
        if (file_exists($str)) {
            $command_line = $command_line . " " . $str;
            $str = fgets($source_file);
            $str = trim($str);
        } else {
            $str = fgets($source_file);
            $str = trim($str);
        }
    }
    fclose($source_file);
    $output = fopen(realpath("./Game/Core/") . "/fluents", 'a') or die("can't open file");
    //parse the logic part
    $ws_pos = str_getcsv($command_line, " ");
    for ($i = 0; $i < count($ws_pos); $i++) {
        if (file_exists($ws_pos[$i])) {
            $r_file = fopen($ws_pos[$i], 'r') or die("can't open file");
            $str = fgets($r_file);
            $end = false;
            while (($str != FALSE) && ($end === FALSE)) {
                switch (trim($str)) {
                    case "fluents:": {
                            fclose($output);
                            $output = fopen(realpath("./Game/Core/") . "/fluents", 'a') or die("can't open file");
                            break;
                        }
                    case "actions:": {
                            fclose($output);
                            $output = fopen(realpath("./Game/Core/") . "/actions", 'a') or die("can't open file");
                            break;
                        }
                    case "always:": {
                            $end = TRUE;
                            break;
                        }
                    case "initially:": {
                            $end = TRUE;
                            break;
                        }
                    case "goal:": {
                            $end = TRUE;
                            break;
                        }
                    default: {
                            fwrite($output, $str);
                            break;
                        }
                }
                $str = fgets($r_file);
            }
        }
    }
    fclose($output);
    fclose($r_file);
    $game_plan = fopen(realpath("./Game/Core/") . "/core.plan", 'w') or die("can't open file");
    $r_file = fopen(realpath("./Game/Core/") . "/fluents", 'r') or die("can't open file");
    fwrite($game_plan, fread($r_file, filesize(realpath("./Game/Core/") . "/fluents")));
    fclose($r_file);
    $r_file = fopen(realpath("./Game/Core/") . "/actions", 'r') or die("can't open file");
    fwrite($game_plan, fread($r_file, filesize(realpath("./Game/Core/") . "/actions")));
    fclose($r_file);
    $r_file = fopen(realpath("./Game/Core/") . "/always", 'r') or die("can't open file");
    fwrite($game_plan, fread($r_file, filesize(realpath("./Game/Core/") . "/always")));
    fclose($r_file);
}
function unlinkOldDeck(){
    $files = glob("./Game/Modules/Decks/*");
    foreach($files as $file){
        unlink($file);
    }
    if(file_exists(realpath("./Game/dummy"))){
        unlink(realpath("./Game/dummy"));
    }
    $file = fopen(realpath("./Game/") . "/timesheet.csv",'w');
    fclose($file);
}
function dumpTime(){
    $w_file = fopen(realpath("./Game/") . "/timesheet.csv",'a');
    fputs($w_file, ($_SESSION["timer"][3]-$_SESSION["timer"][2]) . ";\n");
    fputs($w_file, ($_SESSION["timer"][4]-$_SESSION["timer"][1]) . ";\n");
}
?>
