// the url map for game-related actions.

var Jack = require("jack"),
    HashP = require("hashp").HashP,
    map = {},
    couch = require("./couch").CouchDB("http://localhost:5984/jic-jack-jo"),
    emptyGame = {
        x : null,
        o : null,
        state : [["","",""],["","",""],["","",""]],
        turn : "x",
        win : null
    };

function gameURL (env, game_id) {
    return env["jsgi.url_scheme"]+"://"+env.HTTP_HOST+"/game/"+game_id;
};

function sitDown (user) {
    // see if there is an empty seat.
    var seat = couch.GET("_design/jic-jack-jo/_view/open_seat").rows[0].value;
    var game;
    if (seat[0] === "open") {
        game = couch.GET(seat[1]);
        // make sure i'm not sitting there already...
        if (game) {
            if (game.x !== user && game.o !== user) {
                // sit down
                game[ seat[2] ] = user;
                if (couch.PUT(seat[1], game, true).status !== 201) return sitDown(user);
                return game;
            }
            // already sitting.
            return game;
        }
    }
    // either the seats are all full, or the GET failed.
    game = emptyGame;
    game.x = user;
    game._id = seat[1];
    if (!couch.PUT(seat[1], game, true)) return sitDown(user);
    return game;
};
map["/new"] = require("./allowed-methods").AllowedMethods(function (env) {
    var game = sitDown(env["jjj.user"]),
        location = gameURL(env, game._id);
    return {
        status : 302,
        headers : {
            "Content-Type":"text/plain",
            "Location":location
        },
        body : [JSON.stringify({"error":"Found", "location":location})]
    };
}, ["POST", "PUT", "HEAD", "GET"]);

map["/move"] = require("./move").app;

map["/"] = function (env) {
    
    var id = env.PATH_INFO.replace(/^.*?(game-[0-9]+).*$/g, '$1'),
        game = couch.GET(id);
    
    if (!game) return {
        status : 404,
        headers : {"Content-Type":"application/json"},
        body : [JSON.stringify({error:"not_found"})]
    }
    
    // make sure that it's a proper url.
    var cannonical = "/" + game._id,
        location = gameURL(env, game._id);
    if (env.PATH_INFO !== cannonical) return {
        status : 301,
        headers : {
            "Content-Type":"application/json",
            "Location" : location
        },
        body : [JSON.stringify({"error":"Moved Permanently","location":location})]
    };
    
    game.you = env["jjj.user"];
    
    return {
        status :200,
        headers : {"Content-Type":"application/json"},
        body : [JSON.stringify(game)]
    };
};

exports.app = Jack.URLMap(map);
@@ -531,16 +531,26 @@
 r seat =
+ (%0A       
  couch.G
@@ -602,16 +602,76 @@
 s%5B0%5D
+ %7C%7C %7B%0A            value:%5B %22open%22, %22game-0%22 %5D%0A        %7D%0A    )
 .value;%0A
     
@@ -666,16 +666,21 @@
 .value;%0A
+    %0A
     var 

Handle the case when there are no rows returned from the couchdb view.