package blockchain

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

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

/*
type UserInfo struct {
	Id               int64
	Addr             string
	Direct           string  //我的上级
	DirectNumber     int     //直推总人数
	IndirectRewards  float64 `xorm:"Decimal"`
	Indirect         string  //上上级
	IndirectNumber   int     //间推总人数
	DirectRewards    float64 `xorm:"Decimal"`
	Superiors        string  //所有上级
	AvailableClaim   float64 `xorm:"Decimal"` //可领取收益
	TotalClaimed     float64 `xorm:"Decimal"` //总共已领取的收益
	AvailableReinput float64 `xorm:"Decimal"` //可用复投
	TotalReinputed   float64 `xorm:"Decimal"` //总复投

	ParticipateAmount float64 `xorm:"Decimal"` //总参与

	State  int //身份   0 1正式   2  社区
	OpTime string
	Hash   string
}

type Performance struct {
	Id                      int64
	Addr                    string
	TotalPerformance        float64 `xorm:"Decimal"`
	ClaimedPerformanceLevel int
	PerformanceRewards      float64 `xorm:"Decimal"`

	TotalTeamCultivate    float64 `xorm:"Decimal"`
	ClaimedCultivateLevel int
	TeamCultivateRewards  float64 `xorm:"Decimal"`

	CommunityGift float64 `xorm:"Decimal"`
	CommunityNode float64 `xorm:"Decimal"`
}
*/

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 {
		return err
	}
	if !ok {
		return errors.New("participate get user info failed")
	}

	//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 * controller.Decimals)
	ui.State = 1
	ui.CreateTime = util.NowTimeString()
	ui.Hash = hash

	_, err = engine.Insert(&ui)
	if err != nil {
		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 {
		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 {
			return err
		}
	}
	///update indirect recommend rewards(10%)
	if ui.Indirect != "" {
		err := controller.UpdateAvailableRewards(engine, rewards, ui.Indirect, true, false)
		if err != nil {
			return err
		}
	}

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

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

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