package module

import (
	"fmt"
	"strings"

	"github.com/aliyun/aliyun-tablestore-go-sdk/tablestore"
	"gitlab.alibaba-inc.com/pai_biz_arch/pairec/log"
	"gitlab.alibaba-inc.com/pai_biz_arch/pairec/persist/tablestoredb"
	"gitlab.alibaba-inc.com/pai_biz_arch/pairec/recconf"
)

type User2ItemCustomFilterTableStoreDao struct {
	table      string
	tablestore *tablestoredb.TableStore
}

func NewUser2ItemCustomFilterTableStoreDao(config recconf.FilterConfig) *User2ItemCustomFilterTableStoreDao {
	dao := &User2ItemCustomFilterTableStoreDao{}
	tablestore, err := tablestoredb.GetTableStore(config.DaoConf.TableStoreName)
	if err != nil {
		log.Error(fmt.Sprintf("%v", err))
		return nil
	}
	dao.tablestore = tablestore
	dao.table = config.DaoConf.TableStoreTableName
	return dao
}

func (d *User2ItemCustomFilterTableStoreDao) Filter(uid UID, items []*Item) (ret []*Item) {
	getRowRequest := new(tablestore.GetRowRequest)
	criteria := new(tablestore.SingleRowQueryCriteria)
	putPk := new(tablestore.PrimaryKey)
	putPk.AddPrimaryKeyColumn("user_id", string(uid))

	criteria.PrimaryKey = putPk
	criteria.ColumnsToGet = []string{"item_ids"}
	getRowRequest.SingleRowQueryCriteria = criteria
	getRowRequest.SingleRowQueryCriteria.TableName = d.table
	getRowRequest.SingleRowQueryCriteria.MaxVersion = 1

	getResp, err := d.tablestore.Client.GetRow(getRowRequest)

	if err != nil {
		log.Error(fmt.Sprintf("module=User2ItemCustomFilterTableStoreDao\tuid=%s\terr=%v", uid, err))
		ret = items
		return
	}

	var ids string
	if str, ok := getResp.Columns[0].Value.(string); ok {
		ids = str
	}

	idList := strings.Split(ids, ",")
	if idList == nil {
		ret = items
		return
	}
	fiterIds := make(map[string]bool, len(idList))

	for _, id := range idList {
		fiterIds[id] = true
	}

	for _, item := range items {
		if _, ok := fiterIds[string(item.Id)]; !ok {
			ret = append(ret, item)
		}
	}
	return
}
