package micro

import (
	"context"
	"strings"

	"git.nspix.com/golang/micro/registry"
)

type (
	Options struct {
		Zone                   string            //注册域
		Name                   string            //名称
		Version                string            //版本号
		EnableHttp             bool              //启用HTTP功能
		EnableRPC              bool              //启用RPC功能
		EnableInternalListener bool              //启用内置网络监听服务
		DisableRegister        bool              //禁用注册
		registry               registry.Registry //注册仓库
		Server                 Server            //加载的服务
		Port                   int               //绑定端口
		Address                string            //绑定地址
		EnableHttpPProf        bool              //启用HTTP调试工具
		EnableStats            bool              //启用数据统计
		EnableLogPrefix        bool              //启用日志前缀
		EnableCli              bool              //启用cli模式
		EnableReport           bool              //启用数据上报
		RegistryArguments      map[string]string //注册参数
		Context                context.Context
		shortName              string
	}

	Option func(o *Options)
)

func (o *Options) ShortName() string {
	if o.shortName != "" {
		return o.shortName
	}
	if pos := strings.LastIndex(o.Name, "/"); pos != -1 {
		o.shortName = o.Name[pos+1:]
	} else {
		o.shortName = o.Name
	}
	return o.shortName
}

func WithName(name string, version string) Option {
	return func(o *Options) {
		o.Name = name
		o.Version = version
	}
}

func WithPort(port int) Option {
	return func(o *Options) {
		o.Port = port
	}
}

func WithStats() Option {
	return func(o *Options) {
		o.EnableStats = true
	}
}

func WithHttpDebug() Option {
	return func(o *Options) {
		o.EnableHttpPProf = true
	}
}

func WithCli() Option {
	return func(o *Options) {
		o.EnableCli = true
	}
}

func WithRegistry(r registry.Registry) Option {
	return func(o *Options) {
		o.registry = r
	}
}

func WithServer(s Server) Option {
	return func(o *Options) {
		o.Server = s
	}
}

func WithoutHttp() Option {
	return func(o *Options) {
		o.EnableHttp = false
	}
}

func WithoutRegister() Option {
	return func(o *Options) {
		o.DisableRegister = true
	}
}

func WithoutLogPrefix() Option {
	return func(o *Options) {
		o.EnableLogPrefix = false
	}
}

func WithoutRPC() Option {
	return func(o *Options) {
		o.EnableRPC = false
	}
}

func NewOptions() *Options {
	opts := &Options{
		Zone:                   "default",
		Version:                "1.0.1",
		EnableHttp:             true,
		EnableRPC:              true,
		EnableInternalListener: true,
		EnableLogPrefix:        true,
		EnableReport:           true,
		EnableHttpPProf:        true,
		Context:                context.Background(),
		registry:               registry.DefaultRegistry,
	}
	return opts
}
