package service

import (
	"strings"

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

type CallBackService struct {
	featureService *FeatureService
	User           *module.User
	Items          []*module.Item
}

func NewCallBackService() *CallBackService {
	services := CallBackService{
		featureService: DefaultFeatureService(),
	}
	return &services
}

func (r *CallBackService) LoadLog(context *context.RecommendContext) {
	r.featureService.LoadFeatures(r.User, r.Items, context)
}

func (r *CallBackService) RecordLog(context *context.RecommendContext, msg string) error {
	scene_name := context.GetParameter("scene").(string)
	scene_name = strings.ReplaceAll(scene_name, "_callback", "")
	if callBackConfig, ok := context.Config.CallBackConfs[scene_name]; ok {
		data_source := callBackConfig.DataSource
		if data_source.Type == recconf.DataSource_Type_Kafka {
			return r.RecordToKafka(data_source.Name, msg)
		} else if data_source.Type == recconf.DataSource_Type_Datahub {
			return r.RecordToDatahub(data_source.Name, msg)
		}
	}

	return nil
}

func (r *CallBackService) RecordToKafka(kafka_name string, msg string) error {
	p, error := datasource.GetKafkaProducer(kafka_name)
	if error != nil {
		return error
	}
	p.SendMessage(msg)
	return nil
}

func (r *CallBackService) RecordToDatahub(name string, msg string) error {
	p, error := datahub.GetDatahub(name)
	if error != nil {
		return error
	}
	p.SendMessage([]map[string]interface{}{{"callback_log": msg}})
	return nil
}

func (r *CallBackService) RecordLogList(context *context.RecommendContext, messages []string) error {
	scene_name := context.GetParameter("scene").(string)
	scene_name = strings.ReplaceAll(scene_name, "_callback", "")
	if callBackConfig, ok := context.Config.CallBackConfs[scene_name]; ok {
		data_source := callBackConfig.DataSource
		if data_source.Type == recconf.DataSource_Type_Kafka {
			return r.RecordToKafkaList(data_source.Name, messages)
		} else if data_source.Type == recconf.DataSource_Type_Datahub {
			return r.RecordToDatahubList(data_source.Name, messages)
		}
	}

	return nil
}

func (r *CallBackService) RecordToKafkaList(kafka_name string, messages []string) error {
	p, error := datasource.GetKafkaProducer(kafka_name)
	if error != nil {
		return error
	}
	for _, msg := range messages {
		p.SendMessage(msg)
	}
	return nil
}

func (r *CallBackService) RecordToDatahubList(name string, messages []string) error {
	p, error := datahub.GetDatahub(name)
	if error != nil {
		return error
	}
	var data []map[string]interface{}

	for _, msg := range messages {
		data = append(data, map[string]interface{}{"callback_log": msg})
	}
	p.SendMessage(data)
	return nil
}
