/*
  Copyright (c) 2021 Corinne Diakhoumpa et Erwan Iev-Le Tac

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
*/

const fs = require("fs");
const assert = require('assert').strict;
const utils = require('./utils');

const dump_state = false;
const start = {
    x: 6,
    y: 2,
    orientation: "west",
};
const maze_string = [
    //0 1 2 3 4 5 6 7
    " ─ ─ ─ ─ ─ ─ ─ ─ ",
    "┆ ┆ │ ┆ ┆ ┆ ┆ ┆ │", // 0
    " ─ ┄ ┄ ─ ┄ ─ ─ ─ ",
    "│ ┆ │ ┆ ┆ │ ┆ ┆ │", // 1
    " ┄ ─ ─ ─ ┄ ┄ ─ ┄ ",
    "│ ┆ ┆ ┆ │ │ ┆ ┆ │", // 2
    " ─ ┄ ─ ┄ ┄ ─ ┄ ┄ ",
    "│ │ │ ┆ │ ┆ ┆ │ │", // 3
    " ┄ ┄ ┄ ─ ─ ─ ─ ┄ ",
    "│ ┆ │ ┆ ┆ ┆ ┆ ┆ │", // 4
    " ─ ─ ─ ─ ─ ─ ─ ─ ",
];
const width = (maze_string[0].length - 1) / 2;
const height = (maze_string.length - 1) / 2;

////////////////////////////////////////////////////////////////////////////////
// Parse the maze's string.
let maze = new Array(width);
for (let x = 0; x < width; x++) {
    maze[x] = new Array(height);
    for (let y = 0; y < height; y++) {
        let X = 2 * x + 1;
        let Y = 2 * y + 1;
        maze[x][y] = {
            "west": maze_string[Y].charAt(X - 1) == "┆",
            "east": maze_string[Y].charAt(X + 1) == "┆",
            "north": maze_string[Y - 1].charAt(X) == "┄",
            "south": maze_string[Y + 1].charAt(X) == "┄",
        };
    }
}

////////////////////////////////////////////////////////////////////////////////
// Build all states that can be reached by exploring the maze.
let states = [];
let states_id = new Array(width);
for (let x = 0; x < width; x++) {
    states_id[x] = new Array(height);
    for (let y = 0; y < height; y++)
        states_id[x][y] = {};
}
let stack = [start];
while (stack.length) {
    let state = stack.pop();
    if (states_id[state.x][state.y].hasOwnProperty(state.orientation))
        continue;

    states_id[state.x][state.y][state.orientation] = states.length;
    states.push({
        x: state.x,
        y: state.y,
        orientation: state.orientation,
    });

    if (state.x > 0 && maze[state.x][state.y]["west"])
        stack.push({x: state.x - 1, y: state.y, orientation: "west"});
    if (state.x < width && maze[state.x][state.y]["east"])
        stack.push({x: state.x + 1, y: state.y, orientation: "east"});
    if (state.y > 0 && maze[state.x][state.y]["north"])
        stack.push({x: state.x, y: state.y - 1, orientation: "north"});
    if (state.y < height && maze[state.x][state.y]["south"])
        stack.push({x: state.x, y: state.y + 1, orientation: "south"});
}

////////////////////////////////////////////////////////////////////////////////
// Dump the states as a "gamebook" text.

// Permutate ids for print purpose.
function printed_id(id) {
    // Keep start state at the first position.
    if (id == 0)
        return id + 1;
    // Permute the other states.
    let generator = 229;
    let permuted_id = 1 + (generator * id) % (states.length - 1)
    return permuted_id + 1;
}
const last_id = states.length + 1;

// Describe the choice to go to the new state, depending on current orientation.
const forward = "devant";
const leftward = "gauche";
const backward = "derrière";
const rightward = "droite";
function choice_text(first_choice, choice, printed_id) {
    return `${first_choice ? "Allez en" : "En"} ${printed_id} ${first_choice ? "pour emprunter la porte" : "pour celle"} de ${choice}.`;
}
function relative_direction_choice(current_orientation, new_state, first_choice) {
    let cardinals = ["north", "east", "south", "west"];
    let shift = (cardinals.length +
                 cardinals.indexOf(new_state.orientation) -
                 cardinals.indexOf(current_orientation)) % cardinals.length;
    let choice = [forward, rightward, backward, leftward][shift];
    let id = states_id[new_state.x][new_state.y][new_state.orientation];
    return choice_text(first_choice, choice, printed_id(id));
}

// Dump the text using a markdown syntax.
let text_to_print = new Array(states.length);

states.forEach((state, id) => {
    let text = `**${printed_id(id)}** `;
    if (dump_state) text += `(${state.x},${state.y} ${state.orientation}) `;
    let choices = [];
    if (state.x == 0 && state.y == 0) {
        assert.strictEqual(state.orientation, "west");
        choices.push(choice_text(true, forward, last_id));
    }
    if (state.x > 0 && maze[state.x][state.y]["west"])
        choices.push(relative_direction_choice(state.orientation, {x: state.x - 1, y: state.y, orientation: "west"}, !choices.length));
    if (state.x < width && maze[state.x][state.y]["east"])
        choices.push(relative_direction_choice(state.orientation, {x: state.x + 1, y: state.y, orientation: "east"}, !choices.length));
    if (state.y > 0 && maze[state.x][state.y]["north"])
        choices.push(relative_direction_choice(state.orientation, {x: state.x, y: state.y - 1, orientation: "north"}, !choices.length));
    if (state.y < height && maze[state.x][state.y]["south"])
        choices.push(relative_direction_choice(state.orientation, {x: state.x, y: state.y + 1, orientation: "south"}, !choices.length));

    if (choices.length == 1)
        text += "C'est un cul-de-sac ! ";
    text += choices.join(" ");
    
    text_to_print[printed_id(id) - 1] = text;
});
text_to_print.push(`**${last_id}** Félicitations, vous êtes sorti·e du labyrinthe !\n`)

console.log("Vous êtes perdu·e au milieu d'un labyrinthe composé de pièces carrées reliées entre elles par des portes. Allez en 1 pour tenter de vous en échapper.")
text_to_print.forEach(text => {
    console.log(text);
})

// Generate the map as an SVG image.
const filename = "meandres.svg";
console.log(`Generate ${filename}...`)
let stream = fs.createWriteStream(filename);
let size = 10;
let scale = 1;
stream.write(utils.svgProlog(`height="${(height+1)*scale}cm" width="${(width+1)*scale}cm" viewBox="0 0 ${(width+1)*size} ${(height+1)*size}"`));
stream.write(utils.svgHeaderWithCopyLeft("Dédale", "Plan du labyrinthe."));
stream.write(`<g transform="translate(${size/2},${size/2})"><path stroke-linecap="round" stroke="black" d="`);
for (let x = 0; x < width; x++) {
    for (let y = 0; y < height; y++) {
        if (x == 0 && !maze[x][y]["west"])
            stream.write(`M ${x*size},${y*size} L ${x*size},${(y+1)*size}`);
        if (!maze[x][y]["east"])
            stream.write(`M ${(x+1)*size},${y*size} L ${(x+1)*size},${(y+1)*size}`);
        if (y == 0 && !maze[x][y]["north"])
            stream.write(`M ${x*size},${y*size} L ${(x+1)*size},${y*size}`);
        if (!maze[x][y]["south"])
            stream.write(`M ${x*size},${(y+1)*size} L ${(x+1)*size},${(y+1)*size}`);
    }
}
stream.write(`"/></g>`);
stream.write("</svg>")
stream.end();
console.log("done")