package game

import (
	"encoding/json"
	"fmt"
	"ordonnance/common/auth"
	"ordonnance/common/db"
	"ordonnance/common/util"
	"ordonnance/logger"
	"ordonnance/server/dao"
	"ordonnance/server/model"
	"ordonnance/server/response"
	"strconv"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

// 注册
func Register(c *gin.Context) {
	username, _ := c.GetPostForm("username")
	password, _ := c.GetPostForm("password")
	if len(password) != 32 || len(username) < 3 {
		response.ReturnErrMsg(response.PASSWD_ERR, c)
		return
	}
	if _, err := dao.GetUserByName(username); err == nil {
		logger.Info("user exsit", err.Error())
		response.ReturnErrMsg(response.PLAYER_EXIST, c)
		return
	}
	user := model.User{
		Username: username,
		Nickname: username,
		Password: password,
	}

	if err := db.GDB.Create(&user).Error; err != nil {
		logger.Info("create err", err.Error())
		response.ReturnErrMsg(response.PLAYER_EXIST, c)
		return
	}
	curtime := int(time.Now().UnixNano() / 1000000)
	data := fmt.Sprintf("%d|%d|-1", user.UserId, curtime)
	msg := response.NewMessage(response.OK)
	msg.Token = auth.AesEncrypt(data)
	msg.Uid = user.UserId
	c.JSON(200, msg)
}

// 登入
func Login(c *gin.Context) {
	username, _ := c.GetPostForm("username")
	password, _ := c.GetPostForm("password")

	if len(password) != 32 || len(username) < 3 {
		response.ReturnErrMsg(response.PASSWD_ERR, c)
		return
	}
	user, err := dao.GetUserByName(username)
	if err != nil {
		logger.Info("player null", err.Error())
		response.ReturnErrMsg(response.PLAYER_NOT_EXIST, c)
		return
	}
	curtime := int(time.Now().UnixNano() / 1000000)

	if user.Password != password {
		logger.Info("passwd err ", user.Password, password)
		response.ReturnErrMsg(response.PASSWD_ERR, c)
		return
	}

	data := strconv.Itoa(user.UserId) + "|" + strconv.Itoa(curtime) + "|-1"
	token := auth.AesEncrypt(data)
	msg := response.NewMessage(response.OK)
	msg.Token = token
	msg.Uid = user.UserId

	if v, err := dao.GetValidBulletin(); err == nil {
		msg.Data = v
	}
	c.JSON(200, msg)
}

// 获取服务器
func ServerList(c *gin.Context) {
	token := c.PostForm("token")
	tokenData, err := util.ParseToken(token)
	if err != nil {
		logger.Info("errtoken err ", err.Error())
		response.ReturnErrMsg(response.ERR_PARM, c)
		return
	}
	version := c.DefaultPostForm("version", "A")
	userID := tokenData.UserId
	historyList, _ := dao.GetIUserServerByUid(userID, version)
	serverList, _ := dao.GetAllServer(version)
	retData := struct {
		HistoryList interface{} `json:"historyList"`
		ServerList  interface{} `json:"serverList"`
	}{
		HistoryList: historyList,
		ServerList:  serverList,
	}
	c.JSON(200, retData)
}

func GetGate(c *gin.Context) {
	tokenData, err := util.ParseToken(c.PostForm("token"))
	if err != nil {
		logger.Info("errtoken err ", err.Error())
		response.ReturnErrMsg(response.ERR_PARM, c)
		return
	}
	version := c.DefaultPostForm("version", "B")
	version = strings.TrimSpace(version)
	serverID := c.PostForm("serverId")
	data := fmt.Sprintf("%v|%v|%v|%v", tokenData.UserId, time.Now().UnixNano()/1000000, 0, 2)
	token := auth.AesEncrypt(data)
	rowServer, _ := dao.GetServerInfo(serverID)
	retData := model.Server{
		Server:          map[string]string{"0": rowServer.Name},
		Net:             model.ServerNet{},
		GamePlatform:    rowServer.GamePlatform,
		Path:            model.ServerPath{},
		IsDebugVersions: 1 == rowServer.IsDebugVersions,
		Tpl:             model.ServerTpl{},
		Opendns:         []string{},
		Token:           token,
		RealAuth:        2,
	}
	json.Unmarshal([]byte(rowServer.Net), &retData.Net)
	json.Unmarshal([]byte(rowServer.Tpl), &retData.Tpl)
	json.Unmarshal([]byte(rowServer.Opendns), &retData.Opendns)
	msg := response.NewMessage(response.OK)
	// tmpData, _ := util.ParseToken(token)
	msg.Data = retData
	c.JSON(200, msg)
}
