/*
 * @Descripttion:
 * @version:
 * @Author: Neo,Huang
 * @Date: 2020-10-16 14:29:56
 * @LastEditors: Neo,Huang
 * @LastEditTime: 2020-12-28 09:43:46
 */
package utils

import (
	"fmt"

	"database/sql"
	"log"

	// import sql driver
	_ "github.com/go-sql-driver/mysql"
)

// 获取数据库handler
var mapMysql = make(map[string]*sql.DB)

// GetMysqlHandler getMysqlHandler
func GetMysqlHandler() (*sql.DB, error) {
	var err error
	project := GetProject()

	if mapMysql[project] != nil {
		err = mapMysql[project].Ping()
		if err == nil {
			return mapMysql[project], nil
		}
		log.Print("GetMysqlHandler PING:", err)
		mapMysql[project].Close()
	}

	configFile := GetConfigFile()

	connString := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", //
		GetConf("mysql-game::user", configFile), GetConf("mysql-game::password", configFile),
		GetConf("mysql-game::host", configFile), GetConf("mysql-game::port", configFile), GetConf("mysql-game::database", configFile))

	log.Println("GetMysqlHandler connString:", connString)
	mapMysql[project], err = sql.Open("mysql", connString)
	if err != nil {
		log.Fatal("Open connection failed:", err.Error())
		return nil, err
	}
	err = mapMysql[project].Ping()
	if err != nil {
		log.Print("PING:", err)
		return nil, err
	}

	return mapMysql[project], nil
}

// 更新玩家状态
func UpdatePlayerStatus(uid int, status int) error {
	db, err := GetMysqlHandler()
	if err != nil {
		log.Println("UpdatePlayerStatus GetMysqlHandler, Error: ", err)
		return err
	}

	sql := fmt.Sprintf("UPDATE game_user SET status=%d WHERE uid=%d;", status, uid)
	// log.Println("order_insert_db sql:", sql)
	_, err = db.Exec(sql)
	if err != nil {
		log.Println("UpdatePlayerStatus update data Exec Failed, Error: ", err)
		return err
	}

	return nil
}
