package main

import (
	"github.com/linmadan/egglib-go/core/application"
	"github.com/linmadan/egglib-go/message/publisher/kafka_message/sarama"
	"github.com/linmadan/egglib-go/message/publisher/local_Message"
	"github.com/linmadan/egglib-go/utils/json"
	_ "gitlab.fjmaimaimai.com/mmm-go-pp/egglib-go-demos/orm/go-pg"
	"gitlab.fjmaimaimai.com/mmm-go-pp/egglib-go-demos/pkg/application/factory"
	"gitlab.fjmaimaimai.com/mmm-go-pp/egglib-go-demos/pkg/application/message/command"
	"gitlab.fjmaimaimai.com/mmm-go-pp/egglib-go-demos/pkg/constant"
	"gitlab.fjmaimaimai.com/mmm-go-pp/egglib-go-demos/pkg/log"
	"math"
	"math/rand"
	"time"
)

func main() {
	engineOptions := make(map[string]interface{})
	engineOptions["kafkaHosts"] = constant.KAFKA_HOSTS
	storeOptions := make(map[string]interface{})

	transaction, _ := factory.CreateTransactionContext(nil)
	transaction.StartTransaction()
	defer transaction.RollbackTransaction()
	storeOptions["transactionContext"] = transaction
	local_message.LaunchLocalMessageDispatcher(time.Second*30, "sarama", engineOptions, "pg", storeOptions, log.Logger)

	publisher, err := sarama.NewKafkaSaramaMessagePublisher(constant.KAFKA_HOSTS, log.Logger)
	if err != nil {
		log.Logger.Error(err.Error())
		transaction.RollbackTransaction()
		return
	}
	rand.Seed(time.Now().Unix())
	messages := []*application.Message{
		&application.Message{
			MessageId:   int64(rand.Intn(math.MaxInt32)),
			MessageType: constant.PUSH_MESSAGE_TOPIC,
			MessageBody: json.MarshalToString(command.PushMessageCommand{
				MessageType: 1,
				Title:       "卖家发货通知",
				Content:     "您的商品编号:xxx 已发货",
				SenderUid:   2,
				SenderName:  "买家二号店",
				Receivers: []command.Receiver{
					command.Receiver{ReceiverName: "刘德华", ReceiverUid: 100},
				},
				CompanyId: 999,
			}),
			OccurredOn: time.Now(),
		},
	}
	err = publisher.PublishMessages(messages, nil)
	if err != nil {
		log.Logger.Error(err.Error())
		transaction.RollbackTransaction()
		return
	}
	if err = transaction.CommitTransaction(); err != nil {
		return
	}
	time.Sleep(time.Second * 10)
}