// Copyright 2021 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.

package proto

import (
	"fmt"
	"strings"
)

const (
	PdComponentName                   = "PdConfig"
	TidbComponentName                 = "TidbConfig"
	TikvComponentName                 = "TikvConfig"
	TiflashComponentName              = "TiflashConfig"
	PerformanceDashboardComponentName = "performance.dashboard"
	ConfigType                        = "config"
	PerformanceType                   = "performance"
)

// todo how to get cluster json?
type ClusterJSON struct {
	ClusterName string   `json:"cluster_name"`
	ClusterID   int64    `json:"cluster_id"`  // the id from pd
	DeployType  string   `json:"deploy_type"` // deployment type
	Session     string   `json:"session"`
	BeginTime   string   `json:"begin_time"`
	EndTime     string   `json:"end_time"`
	Collectors  []string `json:"collectors"`
}

type SourceDataV2 struct {
	ClusterInfo   *ClusterJSON
	TidbVersion   string
	NodesData     map[string][]Config // {"component": {config, config, config, nil}}
	DashboardData *DashboardData
}

type HandleData struct {
	UqiTag  string
	Data    []Data
	IsValid bool
}

func (hd *HandleData) checkValid() bool {
	if len(hd.Data) == 0 {
		return false
	}
	for _, data := range hd.Data {
		if data == nil {
			return false
		}
		if conf, ok := data.(Config); ok && conf.CheckNil() {
			return false
		}
	}
	return true
}

func NewHandleData(ds []Data) *HandleData {
	if len(ds) < 1 {
		return &HandleData{UqiTag: "nodata", IsValid: false}
	}
	hd := &HandleData{UqiTag: "", Data: ds}
	htags := make([]string, 0)
	for _, d := range ds {
		conf, ok := d.(Config)
		if ok {
			htags = append(htags, fmt.Sprintf("%s_%s:%d", conf.GetComponent(), conf.GetHost(), conf.GetPort()))
		} else {
			htags = append(htags, d.ActingName())
		}
	}
	hd.UqiTag = strings.Join(htags, "-")
	hd.IsValid = hd.checkValid()
	return hd
}