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

import (
	"github.com/pingcap/tidb-operator/pkg/util/label"
	"github.com/pingcap/tidb-operator/pkg/volumeprovisioner"
	"github.com/pingcap/tidb-operator/test/e2e/framework"
	"k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/resource"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

func testVolumeBestFit(f *framework.Framework) {
	clusterName := "e2e-bestfit"
	var pdCount int32 = 1
	var tidbCount int32 = 2
	var tikvCount int32 = 3

	done := deployCluster(f, e2eNamespace, clusterName, pdCount, tidbCount, tikvCount)

	pvcList, err := f.KubeCli.CoreV1().PersistentVolumeClaims(e2eNamespace).List(label.ClusterListOptions(clusterName))
	Expect(err).NotTo(HaveOccurred())

	pvList, err := f.KubeCli.CoreV1().PersistentVolumes().List(label.ClusterListOptions(clusterName))
	Expect(err).NotTo(HaveOccurred())

	expectedTiKVQuantity := resource.MustParse("60Gi")
	expectedPDQuantity := resource.MustParse("1.2Gi")
	By("And PVC's storage is expected")
	for _, pvc := range pvcList.Items {
		q := pvc.Spec.Resources.Requests[v1.ResourceStorage]
		kind := pvc.Labels[label.AppLabelKey]
		switch kind {
		case label.PDLabelVal:
			if expectedPDQuantity.Cmp(q) != 0 {
				Expect(q.String()).To(Equal(expectedPDQuantity.String()))
			}
		case label.TiKVLabelVal:
			if expectedTiKVQuantity.Cmp(q) != 0 {
				Expect(q.String()).To(Equal(expectedTiKVQuantity.String()))
			}
		default:
			failWrapper("Expect PVC belongs to PD or TiKV")
		}
	}

	By("And PVs are best fit volumes")
	expectedTiKVHostPath := "/tidb/tikv-dir-2"
	expectedPDHostPath := "/tidb/pd-dir-4"
	for _, vol := range pvList.Items {
		hostPath := vol.Annotations[volumeprovisioner.AnnProvisionerHostPath]
		kind := vol.Labels[label.AppLabelKey]
		switch kind {
		case label.PDLabelVal:
			if hostPath != expectedPDHostPath {
				Expect(hostPath).To(Equal(expectedPDHostPath))
			}
		case label.TiKVLabelVal:
			if hostPath != expectedTiKVHostPath {
				Expect(hostPath).To(Equal(expectedTiKVHostPath))
			}
		default:
			failWrapper("Expect PV belongs to PD or TiKV")
		}
	}

	deleteCluster(f, e2eNamespace, clusterName, done, pdCount+tikvCount)
}
