package filter

import (
	"errors"
	"math/rand"

	"gitlab.alibaba-inc.com/pai_biz_arch/pairec/module"
	"gitlab.alibaba-inc.com/pai_biz_arch/pairec/recconf"
)

type AdjustNewItemsFunc func(filterData *FilterData, retainNum int) []*module.Item

var (
	adjustNewItemsFunc = DefaultAdjustNewItemsFunc
)

func DefaultAdjustNewItemsFunc(filterData *FilterData, retainNum int) []*module.Item {
	items := filterData.Data.([]*module.Item)
	newItems := make([]*module.Item, retainNum)

	rand.Shuffle(len(items), func(i, j int) {
		items[i], items[j] = items[j], items[i]
	})

	copy(newItems, items)

	return newItems
}

func RegisterAdjustNewItemsFunc(f AdjustNewItemsFunc) {
	adjustNewItemsFunc = f
}

type AdjustCountFilter struct {
	retainNum int
}

func NewAdjustCountFilter(config recconf.FilterConfig) *AdjustCountFilter {
	filter := AdjustCountFilter{
		retainNum: config.RetainNum,
	}

	return &filter
}
func (f *AdjustCountFilter) Filter(filterData *FilterData) error {
	if _, ok := filterData.Data.([]*module.Item); !ok {
		return errors.New("filter data type error")

	}
	return f.doFilter(filterData)
}

func (f *AdjustCountFilter) doFilter(filterData *FilterData) error {
	items := filterData.Data.([]*module.Item)
	if len(items) <= f.retainNum {
		return nil
	}

	filterData.Data = adjustNewItemsFunc(filterData, f.retainNum)
	return nil
}
