package registry

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/odysseus/service-registry/common"
	"github.com/odysseus/service-registry/query"
	registor "github.com/odysseus/service-registry/registry"
	"os"
)

var querier *query.ServiceQuerier
var redisParam registor.RedisConnParam

type backendService struct {
}

func init() {
	host, _ := beego.AppConfig.String("balancehost")
	db, _ := beego.AppConfig.Int("balancedb")
	pass, _ := beego.AppConfig.String("balancepass")
	redisParam = registor.RedisConnParam{
		Addr:     host,
		Password: pass,
		DbIndex:  db,
	}
	querier = query.NewQuery(redisParam)
}

func NodeManagers() ([]string, error) {
	return querier.Select(common.SERVICE_NODE_MANAGER).List()
}

func Gateways() ([]string, error) {
	return querier.Select(common.SERVICE_API_GATEWAY).List()
}

func Workers() ([]string, error) {
	return querier.Select(common.SERVICE_WORKER).List()
}

func Schedules() ([]string, error) {
	return querier.Select(common.SERVICE_SCHEDULER).List()
}

func NodeManagersByPage(pageSize int, pageNum int) ([]string, int, error) {
	return querier.Select(common.SERVICE_NODE_MANAGER).ListByPage(pageSize, pageNum)
}

func GatewaysByPage(pageSize int, pageNum int) ([]string, int, error) {
	return querier.Select(common.SERVICE_API_GATEWAY).ListByPage(pageSize, pageNum)
}

func WorkersByPage(pageSize int, pageNum int) ([]string, int, error) {
	return querier.Select(common.SERVICE_WORKER).ListByPage(pageSize, pageNum)
}

func SchedulesByPage(pageSize int, pageNum int) ([]string, int, error) {
	return querier.Select(common.SERVICE_SCHEDULER).ListByPage(pageSize, pageNum)
}

func (d backendService) ServiceType() common.ServiceType {
	return common.SERVICE_BACKEND
}

//func (d backendService) Instance() string {
//	hostname, _ := os.Hostname()
//	port, _ := beego.AppConfig.String("httpport")
//	return "http://" + hostname + ":" + port
//}

func (d backendService) Status() string {
	//hostname, _ := os.Hostname()
	//port, _ := beego.AppConfig.String("httpport")
	return "200"
}

func (d backendService) DetailInfo() (json.RawMessage, error) {
	hostname, _ := os.Hostname()
	detail := struct {
		IP       string `json:"ip"`
		HostName string `json:"hostName"`
	}{
		IP:       "",
		HostName: hostname,
	}
	return json.Marshal(detail)
}

func RegistryBackend() {
	r := registor.NewRegistry(redisParam, backendService{})
	go r.Start()
	//time.Sleep(time.Second * 5)
	//r.Stop()
}
