package i18n

import (
	"encoding/json"
	"fmt"
	"github.com/jinzhu/gorm"
	"github.com/pingcap/log"
	"github.com/pingcap/tep/db/entity"
	"go.uber.org/zap"
	"time"
)

type LANG string

const (
	LangZHCN = LANG("zh_CN")
	LangENUS = LANG("en_US")
)

type Bundle struct {
	template map[LANG]map[TemplateID]string
}

func (bundle *Bundle) Format(lang LANG, templateID TemplateID, jsonArrayArgs string) string {
	tempMap, found := bundle.template[lang]
	if !found {
		return fmt.Sprintf("%s %s", string(templateID), jsonArrayArgs)
	}
	template, found := tempMap[templateID]
	if !found {
		return fmt.Sprintf("%s %s", string(templateID), jsonArrayArgs)
	}
	var args = new([]interface{})
	if err := json.Unmarshal([]byte(jsonArrayArgs), args); err != nil {
		log.Error("failed to unmarshal json", zap.String("json", jsonArrayArgs), zap.Error(err))
		return fmt.Sprintf("%s %s", string(templateID), jsonArrayArgs)
	}
	return fmt.Sprintf(template, *args...)
}

func (bundle *Bundle) AddPlatformMessageAndLogError(db *gorm.DB, messageType, templateID string, args ...interface{}) {
	argStrList := make([]string, 0)
	for _, item := range args {
		argStrList = append(argStrList, fmt.Sprintf("%v", item))
	}
	arrJSON, err := json.Marshal(argStrList)
	if err != nil {
		log.Error("failed to marshal args to json", zap.Error(err))
		return
	}
	message := entity.Message{
		Type:              messageType,
		Time:              time.Now().Unix(),
		ContentTemplateID: templateID,
		TemplateArgs:      string(arrJSON),
	}
	err = db.Create(&message).Error
	if err != nil {
		log.Error("add platform message failed", zap.Error(err))
	}
}
