// Copyright 2017 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 spec

package tikv

import (
	"github.com/juju/errors"
	"github.com/ngaut/log"
	"github.com/pingcap/tidb-operator/pkg/util/pdutil"
	"k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/kubernetes/pkg/kubelet/apis"
)

func (tkc *Controller) getNodeLabels(nodeName string) (map[string]string, error) {
	node, err := tkc.kubeCli.CoreV1().Nodes().Get(nodeName, metav1.GetOptions{})
	if err != nil {
		return nil, errors.Trace(err)
	}
	if ls := node.GetLabels(); ls != nil {
		labels := map[string]string{}
		if region, found := ls["region"]; found {
			labels["region"] = region
		}
		if zone, found := ls["zone"]; found {
			labels["zone"] = zone
		}
		if rack, found := ls["rack"]; found {
			labels["rack"] = rack
		}
		if host, found := ls[apis.LabelHostname]; found {
			labels["host"] = host
		}
		return labels, nil
	}
	return nil, errors.Errorf("labels not found")
}

func (tkc *Controller) setStoreLabelsForPod(cli *pdutil.Client, store *pdutil.StoreInfo, pod *v1.Pod) error {
	podName := pod.GetName()
	podNamespace := pod.GetNamespace()
	nodeName := pod.Spec.NodeName
	ls, err := tkc.getNodeLabels(nodeName)
	if err != nil {
		log.Errorf("Node: [%s] has no node labels, skipping set store labels for Pod: [%s/%s]", nodeName, podNamespace, podName)
		return errors.Trace(err)
	}
	log.Debugf("Pod: [%s/%s] is on node: [%s]. Node: [%s]'s labels: %v", podNamespace, podName, nodeName, nodeName, ls)
	updated, err := cli.SetStoreLabels(store, ls)
	if err != nil {
		return errors.Trace(err)
	}
	if updated {
		log.Infof("Pod: [%s/%s] set labels successfully,labels: %v ", podNamespace, podName, nodeName, ls)
	}
	return nil
}
