package main

import (
	"../log"
	"../nt"
	"../rpc"
	"./executor"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"strconv"
)

type JsonBody struct {
	Ids []int64
}

type rpc_params struct{
	Guid string `json:"guid"`
	GameId string `json:"gameId"`
}

func MakeRouter() *gin.Engine {
	r := gin.Default()
	r.GET("/", do_homepage)
	r.POST("/v1/pool/add", do_pool_add)
	r.GET("/v1/pool/query", do_pool_query)
	r.POST("/v1/pool/remove", do_pool_remove)
	r.POST("/v1/pool/pause", do_pool_pause)
	r.POST("/v1/pool/resume", do_pool_resume)
	return r
}

func do_homepage(c *gin.Context) {
	c.String(http.StatusOK, "Welcome to %s v%s", nt.InstName, nt.VERSION)
}

func do_pool_add(c *gin.Context) {
	task_conf := &executor.TaskConf{}
	err := c.BindJSON(task_conf)
	if err != nil {
		c.AbortWithStatus(http.StatusBadRequest)
		return
	}
	task := executor.NewTask(task_conf)
	err = TaskPool.AddTask(task)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"ec": -3,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"ec": 0,
		"id": task.Id,
	})
}

func do_pool_query(c *gin.Context) {

	guid := c.Query("guid")
	if len(guid) == 0 {
		c.JSON(http.StatusOK, gin.H{
			"ec": -4,
		})
		return
	}

	tasks := TaskPool.Tasks()

	for _, t := range tasks {
		if strconv.FormatInt(t.Id,10) == guid {
			c.JSON(http.StatusOK, gin.H{
				"ec": 0,
				"task": t,
			})
			return
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"ec": -5,
	})

}

func do_pool_remove(c *gin.Context) {
	jb := &JsonBody{}
	err := c.BindJSON(jb)
	if err != nil {
		c.AbortWithStatus(http.StatusBadRequest)
		return
	}

	TaskPool.RemoveTasks(jb.Ids...)
	c.JSON(http.StatusOK, gin.H{"ec": 0})
}

func do_pool_pause(c *gin.Context) {
	jb := &JsonBody{}
	err := c.BindJSON(jb)
	if err != nil {
		c.AbortWithStatus(http.StatusBadRequest)
		return
	}

	TaskPool.PauseTasks(jb.Ids...)
	c.JSON(http.StatusOK, gin.H{"ec": 0})
}

func do_pool_resume(c *gin.Context) {
	jb := &JsonBody{}
	err := c.BindJSON(jb)
	if err != nil {
		c.AbortWithStatus(http.StatusBadRequest)
		return
	}

	TaskPool.ResumeTasks(jb.Ids...)
	c.JSON(http.StatusOK, gin.H{"ec": 0})
}

type balanceNtf struct {
	Guid uint64 `json:"guid"`
	Balance int64 `json:"balance"`
}

func notifyClientByLobby(guid uint64, banlance int64) {
	addr, err := rpc.GetUserAgentRpcUrl(guid)
	param := &balanceNtf{guid,banlance}
	args := &rpc.RpcArgs{"ntf_client",param}
	var res rpc.RpcResult
	err = rpc.RpcRequest(addr, args, &res)
	if nil != err {
		log.Debug("notifyClientByLobby",zap.String("rpcUrl",addr),zap.Any("lobbyurl",nt.DynConf.Lobbies),zap.Error(err), zap.Uint64("guid", guid),zap.Any("param", param))
	}
}
