package module

import (
	"gitlab.alibaba-inc.com/pai_biz_arch/pairec/context"
	"gitlab.alibaba-inc.com/pai_biz_arch/pairec/recconf"
	"gitlab.alibaba-inc.com/pai_biz_arch/pairec/service/hook"
)

type GenerateItemDataFunc func(uid UID, item *Item) string

var generateItemDataFuncMap map[string]GenerateItemDataFunc

func init() {
	generateItemDataFuncMap = make(map[string]GenerateItemDataFunc)
}

func RegisterGenerateItemDataFunc(name string, f GenerateItemDataFunc) {
	generateItemDataFuncMap[name] = f
}

func getGenerateItemDataFunc(name string) GenerateItemDataFunc {
	if f, exist := generateItemDataFuncMap[name]; exist {
		return f
	} else {
		return defaultGenerateItemDataFunc
	}
}

// default function
func defaultGenerateItemDataFunc(uid UID, item *Item) string {
	return string(item.Id)
}

type User2ItemExposureDao interface {
	LogHistory(user *User, items []*Item, context *context.RecommendContext)
	FilterByHistory(uid UID, ids []*Item) (ret []*Item)
}

func NewUser2ItemExposureDao(config recconf.FilterConfig) User2ItemExposureDao {
	var dao User2ItemExposureDao
	if config.DaoConf.AdapterType == recconf.DaoConf_Adapter_Mysql {
		dao = NewUser2ItemExposureMysqlDao(config)
	} else if config.DaoConf.AdapterType == recconf.DaoConf_Adapter_TableStore {
		dao = NewUser2ItemExposureTableStoreDao(config)
	} else if config.DaoConf.AdapterType == recconf.DaoConf_Adapter_Hologres {
		dao = NewUser2ItemExposureHologresDao(config)
	} else if config.DaoConf.AdapterType == recconf.DaoConf_Adapter_Redis {
		dao = NewUser2ItemExposureRedisDao(config)
	} else {
		panic("not found User2ItemExposureDao implement")
	}

	if config.WriteLog == true {
		hook.AddRecommendCleanHook(func(dao User2ItemExposureDao) hook.RecommendCleanHookFunc {

			return func(context *context.RecommendContext, params ...interface{}) {
				user := params[0].(*User)
				items := params[1].([]*Item)
				dao.LogHistory(user, items, context)
			}
		}(dao))
	}

	return dao
}
