// 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 controller

import (
	"fmt"
	"math"

	"github.com/ngaut/log"

	"github.com/pingcap/tidb-operator/pkg/apis/pingcap.com/v1"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/resource"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

const (
	defaultPushgatewayImage = "prom/pushgateway:v0.3.1"
)

// tikv uses GB, TB as unit suffix, but it actually means GiB, TiB
func tikvCapacityArgs(limits *v1.ResourceRequirement) string {
	defaultArgs := "--capacity=0"
	if limits == nil {
		return defaultArgs
	}
	q, err := resource.ParseQuantity(limits.Storage)
	if err != nil {
		log.Warnf("failed to parse quantity %s: %v", limits.Storage, err)
		return defaultArgs
	}
	i, b := q.AsInt64()
	if !b {
		log.Warnf("quantity %s can't be converted to int64", q.String())
		return defaultArgs
	}
	return fmt.Sprintf("--capacity=%dGB", int(float64(i)/math.Pow(2, 30)))
}

func getOwnerRef(cluster *v1.TidbCluster) metav1.OwnerReference {
	controller := true
	return metav1.OwnerReference{
		APIVersion: ControllerKind.GroupVersion().String(),
		Kind:       ControllerKind.Kind,
		Name:       cluster.GetName(),
		UID:        cluster.GetUID(),
		Controller: &controller,
	}
}

func getPushgatewayImage(cluster *v1.TidbCluster) string {
	if img, ok := cluster.Annotations["pushgateway-image"]; ok && img != "" {
		return img
	}
	return defaultPushgatewayImage
}

func getServiceType(services []v1.Service, kind string) corev1.ServiceType {
	for _, svc := range services {
		if svc.Name == kind {
			switch svc.Type {
			case "NodePort":
				return corev1.ServiceTypeNodePort
			case "LoadBalancer":
				return corev1.ServiceTypeLoadBalancer
			default:
				return corev1.ServiceTypeClusterIP
			}
		}
	}
	return corev1.ServiceTypeClusterIP
}

func pdSetNameFor(tc *v1.TidbCluster) string {
	return fmt.Sprintf("%s-pdset", tc.GetName())
}

func tidbSetNameFor(tc *v1.TidbCluster) string {
	return fmt.Sprintf("%s-tidbset", tc.GetName())
}

func tikvSetNameFor(tc *v1.TidbCluster) string {
	return fmt.Sprintf("%s-tikvset", tc.GetName())
}

func secretNameFor(tc *v1.TidbCluster) string {
	return fmt.Sprintf("%s-secret", tc.GetName())
}
