package main

import (
	"bytes"
	"encoding/json"
	"net/http"
	"werwolf/core"
)

var games []JSON_Game

type JSON_Game struct {
	Token    string `json:"token"`
	Username string `json:"username"`
	Gamename string `json:"gamename"`
}

// getGame returns a reference to a game-Object identified by token
func getGame(token string) (*JSON_Game, bool) {
	for _, g := range games {
		if g.Token == token {
			return &g, true
		}
	}
	return nil, false
}

// addGame adds a game-Object game to the list of active games or replaces an inactive game.
func addGame(game JSON_Game) bool {
	a := true
	for _, g := range games {
		if g.Token == "" {
			g = game
			a = false
			return true
		}
	}
	if a {
		games = append(games, game)
	}
	return true
}

// removeGame disables a game-Object by setting its token to none. Object to be edited is identified by token. Returns true if successfull or false if not found.
func removeGame(token string) bool {
	for _, g := range games {
		if g.Token == token {
			g.Token = ""
			return true
		}
	}
	return false
}

func newGame(responseWriter http.ResponseWriter, request *http.Request) {
	var game = new(JSON_Game)
	buf := new(bytes.Buffer)
	buf.ReadFrom(request.Body)

	if json.Unmarshal(buf.Bytes(), game) == nil {
		game.Token = randomString(32)
		if addGame(*game) {
			core.SendObject(&responseWriter, game)
			addGame(*game)
		} else {
			sendError(&responseWriter, "game_creation")
		}
	} else {
		sendError(&responseWriter, "json")
	}
}

func joinGame(responseWriter http.ResponseWriter, request *http.Request) {
	var game = new(JSON_Game)
	buf := new(bytes.Buffer)
	buf.ReadFrom(request.Body)

	if json.Unmarshal(buf.Bytes(), game) == nil {
		game, succ := getGame(game.Token)
		if succ {
			core.SendObject(&responseWriter, *game)
		} else {
			sendError(&responseWriter, "game_notfound")
		}
	} else {
		sendError(&responseWriter, "json")
	}
}

func sendError(responseWriter *http.ResponseWriter, errorMsg string) {
	core.SendObject(responseWriter, map[string]string{"state": errorMsg + "_error"})
}
