package main

import (
	"encoding/json"
	"log"
	"os"
	
	"battlecamp-go-server/stomp"
	"battlecamp-go-server/flag"
	"battlecamp-go-server/events"
	"battlecamp-go-server/player"
)

var Server *string

func main() {
	initLogging()
	log.Println("Game bot version 0.1")
	
	flag.ParseFlags()
	go subscribeToGame()
	subscribeToUpdate()
}

func subscribeToGame() {
	sub := stomp.Subscribe("game")
	
	for {
		announcement := <- sub
		gs := new(events.GameStart)
		json.Unmarshal(announcement.Body, &gs)
		log.Printf("announcement type: %v ", gs.Type)
		gameEndChan := make(chan bool)
		if("GAME_START" == gs.Type) {
			go joinGame(gs.GameId, gameEndChan)
		} else {
			gameEndChan <- true
		}
	}
}


func subscribeToUpdate() {
	sub := stomp.Subscribe("update")
	
	for {
		announcement := <- sub
		if("vnd.battlecamp.player" == announcement.ContentType) {
			p := new(player.Player)
			json.Unmarshal(announcement.Body, &p)
			playerJoin(p)
		} else {
			pu := new(events.PlayerUpdate)
			json.Unmarshal(announcement.Body, &pu)
			playerUpdate(pu)
		}
	}
}

func joinGame(gameId int64, gameEndChan chan bool) {
	//join game
	
	//retrieve board
	
	for {
		select {
			case <-gameEndChan:
				return
			default:
				move()
		}
	}
}

func move() {
	
}

func playerJoin(p *player.Player) {
	
}

func playerUpdate(pu *events.PlayerUpdate) {
	
}

func initLogging() {
	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)
	}
}
