package controller

import (
	"errors"
	"ktogame/models"
	"strings"

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

func UpdateSuperiorsPerformance(engine *xorm.Engine, superiorsStr string, amount float64) error {
	ids := strings.Split(superiorsStr, ",")
	if len(ids) <= 0 {
		return nil
	}
	var supers []models.UserInfo
	for _, sid := range ids {
		var tmpUser models.UserInfo
		ok, err := engine.Id(sid).Get(&tmpUser)
		if err != nil {
			return err
		}
		if !ok {
			return errors.New("UpdateSuperiorsPerformance get super failed")
		}
		supers = append(supers, tmpUser)
	}

	var rp models.RewardsPool
	_, err := engine.Id(1).Get(&rp)
	if err != nil {
		return err
	}

	for _, user := range supers {
		var per models.Performance
		ok, err := engine.Id(user.Addr).Get(&per)
		if err != nil {
			return err
		}
		if !ok {
			return errors.New("UpdateSuperiorsPerformance get performance failed")
		}

		per.TotalPerformance += amount
		var level int = 0
		for i := 1; i < len(PerformanceLevel); i++ {
			if PerformanceLevel[i-1] <= per.TotalPerformance && per.TotalPerformance < PerformanceLevel[i] {
				level = i
				break
			}
		}
		if level > 0 {
			if level > per.ClaimedPerformanceLevel {
				ratio := PerformanceRatio[level] - PerformanceRatio[per.ClaimedPerformanceLevel]
				rewards := amount * ratio
				if rp.TeamPerformance >= rewards {
					rp.TeamPerformance -= rewards     //pool sub rewards
					per.PerformanceRewards += rewards //user add rewards to PerformanceRewards
					per.ClaimedPerformanceLevel = level
					//update available
					err := UpdateAvailableRewards(engine, rewards, user.Id)
					if err != nil {
						return err
					}

					_, err = engine.ID(user.Addr).Update(&per)
					if err != nil {
						return err
					}
				}
			}
		}
	}

	_, err = engine.ID(1).Update(&rp)
	if err != nil {
		return err
	}

	return nil
}

func UpdateRewardsPool(engine *xorm.Engine, amount float64) error {
	var rp models.RewardsPool
	rp.Recommendation = amount * 0.2
	rp.TeamPerformance = amount * 0.2
	rp.CommunityGift = amount * 0.5
	rp.TeamCultivate = amount * 0.05
	rp.CommunityNode = amount * 0.05
	_, err := engine.ID(1).Update(&rp)
	if err != nil {
		return err
	}
	return nil
}

func UpdateAvailableRewards(engine *xorm.Engine, rewards float64, uid int64) error {
	a_rewards := rewards * 60 / 100
	a_reinput := rewards * 40 / 100
	var user models.UserInfo
	ok, err := engine.Id(uid).Get(&user)
	if err != nil {
		return err
	}
	if !ok {
		return errors.New("engine get failed")
	}
	user.AvailableClaim = a_rewards
	user.AvailableReinput = a_reinput
	_, err = engine.ID(user.Addr).Cols("available_claim").Update(&user)
	if err != nil {
		return err
	}
	_, err = engine.ID(user.Addr).Cols("available_reinput").Update(&user)
	if err != nil {
		return err
	}
	return nil
}
