package clientgo

import (
	"encoding/json"
	"strconv"
	"time"
)

type Error struct {
	ErrorCode int    `json:"error-code"`
	ErrorMsg  string `json:"error-msg"`
}

func NewError(code int, msg string) *Error {
	return &Error{
		ErrorCode: code,
		ErrorMsg:  msg,
	}
}

type Pod struct {
	Name    string `json:"name"`
	Address string `json:"address"`
}

type Cluster struct {
	Pool string `json:"pool"`
	Port uint   `json:"port"`
	Pods []*Pod `json:"pods"`
}

func (c *Cluster) GetPodsUrls() []string {
	urls := make([]string, len(c.Pods))
	for i, pod := range c.Pods {
		urls[i] = pod.Address
	}
	return urls
}

type Request struct {
	KeyspaceID  *string `json:"keyspace_id,omitempty"`
	TenantToken *string `json:"tenant_token,omitempty"`
}

type Response struct {
	Error   *Error   `json:"error,omitempty"`
	Cluster *Cluster `json:"cluster,omitempty"`
}

func (r *Response) String() string {
	bytes, _ := json.Marshal(r)
	return string(bytes)
}

type DumpResponse struct {
	Error     *Error     `json:"error,omitempty"`
	Clusters  []*Cluster `json:"clusters,omitempty"`
	Timestamp int64      `json:"timestamp,omitempty"`
}

func (r *DumpResponse) String() string {
	bytes, _ := json.Marshal(r)
	return string(bytes)
}

type TopologyResult struct {
	HasError  int      `json:"hasError"`
	ErrorInfo string   `json:"errorInfo"`
	State     string   `json:"state"`
	Topology  []string `json:"topology"`
	Timestamp string   `json:"timestamp"`
}

func NewTopologyResult(err error, topo []string) TopologyResult {
	result := TopologyResult{
		HasError:  0,
		ErrorInfo: "",
		State:     "resumed",
		Topology:  topo,
		Timestamp: strconv.FormatInt(time.Now().UnixNano(), 10),
	}
	if err != nil {
		result.HasError = 1
		result.ErrorInfo = err.Error()
	}
	return result
}

func (t *TopologyResult) String() string {
	bytes, _ := json.Marshal(t)
	return string(bytes)
}
