/*
Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved.
Authors:
Petr Krutov, <petr.krutov@digitalenergy.online>
Stanislav Solovev, <spsolovev@digitalenergy.online>
Kasim Baybikov, <kmbaybikov@basistech.ru>

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,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/*
Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud
Orchestration Technology) with Terraform by Hashicorp.

Source code: https://repository.basistech.ru/BASIS/terraform-provider-decort

Please see README.md to learn where to place source code so that it
builds seamlessly.

Documentation: https://repository.basistech.ru/BASIS/terraform-provider-decort/wiki
*/

package k8s

import (
	"context"
	"fmt"
	"strconv"
	"strings"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
	log "github.com/sirupsen/logrus"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/compute"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
)

func utilityDataK8sWgCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*k8s.ItemK8SGroup, []compute.RecordCompute, error) {
	c := m.(*controller.ControllerCfg)

	k8sId := uint64(d.Get("k8s_id").(int))
	wgId := uint64(d.Get("wg_id").(int))

	k8sGetReq := k8s.GetRequest{
		K8SID: k8sId,
	}

	cluster, err := c.CloudAPI().K8S().Get(ctx, k8sGetReq)
	if err != nil {
		return nil, nil, err
	}

	curWg := k8s.ItemK8SGroup{}
	for _, wg := range cluster.K8SGroups.Workers {
		if wg.ID == wgId {
			curWg = wg
			break
		}
	}
	if curWg.ID == 0 {
		return nil, nil, fmt.Errorf("WG with id %v in k8s cluster %v not found", wgId, k8sId)
	}

	workersComputeList := make([]compute.RecordCompute, 0)
	for _, info := range curWg.DetailedInfo {
		compute, err := utilityComputeCheckPresence(ctx, d, m, info.ID)
		if err != nil {
			return nil, nil, err
		}

		workersComputeList = append(workersComputeList, *compute)
	}

	return &curWg, workersComputeList, nil
}

func utilityK8sWgCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*k8s.ItemK8SGroup, error) {
	c := m.(*controller.ControllerCfg)
	var wgId int
	var k8sId int
	var err error

	if strings.Contains(d.Id(), "#") {
		wgId, err = strconv.Atoi(strings.Split(d.Id(), "#")[1])
		if err != nil {
			return nil, err
		}
		k8sId, err = strconv.Atoi(strings.Split(d.Id(), "#")[0])
		if err != nil {
			return nil, err
		}
	} else {
		wgId, err = strconv.Atoi(d.Id())
		if err != nil {
			return nil, err
		}
		k8sId = d.Get("k8s_id").(int)
	}

	req := k8s.GetRequest{
		K8SID: uint64(k8sId),
	}

	cluster, err := c.CloudAPI().K8S().Get(ctx, req)
	if err != nil {
		return nil, err
	}

	for _, wg := range cluster.K8SGroups.Workers {
		if wg.ID == uint64(wgId) {
			return &wg, nil
		}
	}

	return nil, fmt.Errorf("not found wg with id: %v in k8s cluster: %v", wgId, cluster.ID)
}

func  utilityK8sWgListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (k8s.ListK8SGroups, error) {
	c := m.(*controller.ControllerCfg)
	req := k8s.GetRequest{
		K8SID: uint64(d.Get("k8s_id").(int)),
	}

	cluster, err := c.CloudAPI().K8S().Get(ctx, req)
	if err != nil {
		return nil, err
	}

	return cluster.K8SGroups.Workers, nil
}

func utilityK8sWgCloudInitCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (string, error) {
	c := m.(*controller.ControllerCfg)
	req := k8s.GetWorkerNodesMetaDataRequest{
		K8SID: uint64(d.Get("k8s_id").(int)),
		WorkersGroupID: uint64(d.Get("wg_id").(int)),
	}

	cloudInit, err := c.CloudAPI().K8S().GetWorkerNodesMetaData(ctx, req)
	if err != nil {
		return "", err
	}

	return cloudInit, nil
}

func cloudInitDiffSupperss(key, oldVal, newVal string, d *schema.ResourceData) bool {
	if newVal != "" && newVal != oldVal {
		log.Debugf("networkSubresIPAddreDiffSupperss: key=%s, oldVal=%q, newVal=%q -> suppress=FALSE", key, oldVal, newVal)
		return false
	}
	log.Debugf("networkSubresIPAddreDiffSupperss: key=%s, oldVal=%q, newVal=%q -> suppress=TRUE", key, oldVal, newVal)
	return true // suppress difference
}
