package db

import (
	"World/common"
	"common/beegomap"
	"common/logger"
	"encoding/json"
	"errors"
	"fmt"
)

var (
	m_platformIncome *beegomap.BeeMap //make(map[int]*common.PlatformIncomeInfo)
)

func CheckAndLoadPlatformIncome(uid uint32) error {
	if m_platformIncome.Check(uint32(uid)) {
		return nil
	}
	return LoadPlatformIncome(int(uid))
}

func LoadPlatformIncome(uid int) error {
	cmd := fmt.Sprintf("select data from t_platform_income where uid = %d", uid)

	//glog.Info("select sql:", cmd, " uid:", uid)

	rows, err := m_game_db.Query(cmd)
	if rows != nil {
		defer rows.Close()
	}
	if err != nil {
		logger.Notic("mysql select error:%v", err)
		return err
	}

	for rows.Next() {
		var value string
		err = rows.Scan(&value)
		if err != nil {
			logger.Notic("mysql handle result error:%v", err)
			return err
		}
		var data common.PlatformIncomeInfo
		err = json.Unmarshal([]byte(value), &data)
		if err != nil {
			//glog.Info
			logger.Notic("unmarshal json failed:%v for:%v", err, value)
			return err
		}
		m_platformIncome.Set(uint32(uid), &data)

		break
	}
	return nil
}

func GetPlatformIncome(uid int) (*common.PlatformIncomeInfo, error) {
	vv := m_platformIncome.Get(uint32(uid))
	if vv != nil {
		v := vv.(*common.PlatformIncomeInfo)
		return v, nil
	}
	return nil, errors.New("not found")
}

func UpdatePlatformIncome(uid int, platform *common.PlatformIncomeInfo) {
	m_platformIncome.Set(uint32(uid), platform)
	return
}

func SyncPlatformIncomeToDB(uid int) {
	vv := m_platformIncome.Get(uint32(uid))
	if vv != nil {
		data := vv.(*common.PlatformIncomeInfo)
		tmp, _ := json.Marshal(data)
		cmd := "replace into t_platform_income values(?, ?)"
		rows, err := m_game_db.Query(cmd, uid, string(tmp))
		if rows != nil {
			defer rows.Close()
		}
		if err != nil {
			logger.Notic("mysql update error:%v for sql:", err, cmd)
		} else {
			logger.Info("mysql update success for sql:%v", cmd)
		}
	}
}
