package blockchain

import (
	"ktogame/controller"
	"ktogame/models"
	"ktogame/util"
	"strconv"

	"github.com/astaxie/beego/logs"

	"github.com/go-xorm/xorm"
)

func participate(engine *xorm.Engine, user, inviter, hash string, amount float64) error {
	var dui models.UserInfo
	ok, err := engine.Id(inviter).Get(&dui)
	if err != nil {
		logs.Info(err)
		return err
	}
	if !ok {
		//return errors.New("participate get user info failed")
		dui.Id = -1
		dui.Direct = ""
		dui.Superiors = "-1"
	}

	//insert new user info
	var ui models.UserInfo
	ui.Addr = user
	ui.Direct = inviter
	ui.Indirect = dui.Direct
	ui.Superiors = dui.Superiors + "," + strconv.FormatInt(dui.Id, 10)
	ui.ParticipateAmount = float64(controller.PARTICIPATEVALUE)
	ui.State = 1
	ui.CreateTime = util.NowTimeString()
	ui.Hash = hash

	_, err = engine.Insert(&ui)
	if err != nil {
		logs.Info(err)
		return err
	}

	//insert new user Performance
	var uper models.Performance
	uper.Addr = user
	_, err = engine.Insert(&uper)
	if err != nil {
		return err
	}

	//update rewards pool
	err = controller.UpdateRewardsPool(engine, amount)
	if err != nil {
		logs.Info(err)
		return err
	}

	///update Recommendation Rewards
	///update direct recommend rewards(10%)
	rewards := amount * 10 / 100
	if ui.Direct != "" {
		err := controller.UpdateAvailableRewards(engine, rewards, ui.Direct, true, true)
		if err != nil {
			logs.Info(err)
			return err
		}
	}
	///update indirect recommend rewards(10%)
	if ui.Indirect != "" {
		err := controller.UpdateAvailableRewards(engine, rewards, ui.Indirect, true, false)
		if err != nil {
			logs.Info(err)
			return err
		}
	}

	//update all supers performance (15%)
	err = controller.UpdateSuperiorsPerformance(engine, ui.Superiors, amount)
	if err != nil {
		logs.Info(err)
		return err
	}

	//update Community Gift(50%)
	err = controller.UpdateCommunityGift(engine, amount, inviter)
	if err != nil {
		logs.Info(err)
		return err
	}

	//Update Community Nodes(5%)
	err = controller.UpdateCommunityNodes(engine, amount)
	if err != nil {
		logs.Info(err)
		return err
	}

	//update Market(10%)
	err = controller.UpdateMarket(engine, amount)
	if err != nil {
		logs.Info(err)
		return err
	}
	return nil
}

func checkClaim(engine *xorm.Engine, addr, hash, sign string, amount float64) error {
	var tx models.ClaimedTxs
	ok, err := engine.Id(hash).Get(&tx)
	if err != nil {
		return err
	}
	if !ok {
		//set record
		claimTx := models.ClaimedTxs{Addr: addr, Amount: amount, Hash: hash,
			Signature: sign, State: 1, Droped: 0, CreateTime: util.NowTimeString()}
		_, err := engine.Insert(&claimTx)
		if err != nil {
			return err
		}
	} else {
		tx.State = 1
		_, err = engine.ID(hash).Cols("hash").Update(&tx)
		if err != nil {
			return err
		}
	}
	return nil
}
