package service

import (
	"errors"
	"fmt"

	"config-server/conf"

	"github.com/nats-io/nats.go"
	"infish.cn/comm"
)

// 获取部署包内的配置的replayer
func NewConfigReplyer(config *conf.AppConf) *comm.NatsMsgReplyer {
	return &comm.NatsMsgReplyer{
		Subject: "request.configer",
		Entity:  func() interface{} { return &comm.ReqConfiger{} },
		Cb2: func(msg *nats.Msg, entity interface{}) (interface{}, error) {
			cnfs := config.Configer
			if len(cnfs) == 0 {
				return nil, errors.New("no config")
			}
			req := entity.(*comm.ReqConfiger)
			var result string
			for _, v := range cnfs {
				if v.Name == req.Name {
					result = v.Value
					break
				}
			}

			fmt.Println("request.configer=>", result)
			return result, nil
		},
	}
}

// 获取开发环境配置
func NetDevConfigReplyer(config *conf.AppConf) *comm.NatsMsgReplyer {
	return &comm.NatsMsgReplyer{
		Subject: "request.configer.dev",
		Entity:  func() interface{} { return &comm.ReqConfiger{} },
		Cb2: func(msg *nats.Msg, entity interface{}) (interface{}, error) {
			cnfs := config.Configer
			if len(cnfs) == 0 {
				return nil, errors.New("no config")
			}
			req := entity.(*comm.ReqConfiger)
			var result string
			for _, v := range cnfs {
				if v.Name == req.Name {
					result = v.DevValue
					if len(result) < 1 {
						result = v.Value
					}
					break
				}
			}
			fmt.Println("request.configer.dev=>", result)
			return result, nil
		},
	}
}
