package db

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

var (
	m_proxyIncome *beegomap.BeeMap //make(map[int]*common.ProxyIncomeInfo)
)

func CheckAndLoadProxyIncome(uid uint32) error {
	if m_proxyIncome.Check(uint32(uid)) {
		return nil
	}
	return LoadProxyIncome(int(uid))
}

func LoadProxyIncome(uid int) error {
	cmd := fmt.Sprintf("select data from t_proxy_income where uid = %d", 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
	}

	//glog.Info("load mysql club_income start sql:", cmd)

	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.ProxyIncomeInfo
		err = json.Unmarshal([]byte(value), &data)
		if err != nil {
			//glog.Info
			logger.Notic("unmarshal json failed:%v for:", err, value)
			return err
		}
		m_proxyIncome.Set(uint32(uid), &data)

		break
	}
	return nil
}

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

func UpdateProxyIncome(uid int, user *common.ProxyIncomeInfo) {
	m_proxyIncome.Set(uint32(uid), user)
	return
}

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