package main

import (
	"fmt"
	"net"
	"golang.org/x/net/netutil"
	"battlecamp-go-server/board"
	"log"
	"net/http"
	"os"
	"strconv"
)

func main() {
	fmt.Println("Board generator version 0.1")
	logFile, err := os.Create("server.log")

	if err == nil {
		log.SetOutput(logFile)
	} else {
		log.Println("ERROR: Cannot open log file, using console.")
		log.Printf("%v=n", err)
	}

	http.HandleFunc("/", generateBoard)
	http.HandleFunc("/status", status)
	l, _ := net.Listen("tcp", ":8081")
	limitListerer := netutil.LimitListener(l, 100)
	log.Fatal(http.Serve(limitListerer, nil))
}

func generateBoard(w http.ResponseWriter, r *http.Request) {
	x, _ := strconv.Atoi(r.FormValue("x"))
	y, _ := strconv.Atoi(r.FormValue("y"))
	width, _ := strconv.Atoi(r.FormValue("width"))
	height, _ := strconv.Atoi(r.FormValue("height"))
	totalWidth, _ := strconv.Atoi(r.FormValue("totalWidth"))
	totalHeight, _ := strconv.Atoi(r.FormValue("totalHeight"))
	log.Printf("Creating partial x=%v, y=%v, width=%v, height=%v, totalWidth=%v, totalHeight=%v", x, y, width, height, totalWidth, totalHeight)
	b := board.NewRegion(x, y, width, height, totalWidth, totalHeight)
	b.WriteData(w)
}

func status(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("ok"))
}
