/*
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"
	"strconv"
	"strings"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
	"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 handleWorkersChange(ctx context.Context, d *schema.ResourceData, c *controller.ControllerCfg, cluster *k8s.RecordK8S) error {
	o, n := d.GetChange("workers")
	old_set, _ := o.([]interface{})
	new_set, _ := n.([]interface{})
	old_len := len(old_set)
	new_len := len(new_set)

	if old_len > new_len {
		deleted := workersDifference(old_set, new_set)
		if err := deleteWGs(ctx, c, cluster, deleted); err != nil {
			return err
		}

	} else if old_len < new_len {
		added := workersDifference(old_set, new_set)
		if err := addWGs(ctx, c, cluster, added); err != nil {
			return err
		}
	}

	if err := updateNum(ctx, c, cluster, old_set, new_set); err != nil {
		return err
	}

	return nil
}

func updateNum(ctx context.Context, c *controller.ControllerCfg, cluster *k8s.RecordK8S, old_set []interface{}, new_set []interface{}) error {
	for _, valOld := range old_set {
		wgOld, _ := valOld.(map[string]interface{})
		for _, valNew := range new_set {
			wgNew, _ := valNew.(map[string]interface{})
			if wgOld["id"] == wgNew["id"] {
				oldNum := wgOld["num"].(int)
				newNum := wgNew["num"].(int)

				if oldNum < newNum {
					req := k8s.WorkerAddRequest{
						K8SID:          cluster.ID,
						WorkersGroupID: uint64(wgNew["id"].(int)),
						Num:            uint64(newNum - oldNum),
						Chipset:        wgNew["chipset"].(string),
					}

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

				} else if oldNum > newNum {
					for i := oldNum - 1; i >= newNum; i-- {
						detailedInfo := wgOld["detailed_info"].([]interface{})
						if len(detailedInfo) == 0 {
							return nil
						}

						req := k8s.DeleteWorkerFromGroupRequest{
							K8SID:          cluster.ID,
							WorkersGroupID: uint64(wgNew["id"].(int)),
							WorkerID:       uint64(detailedInfo[i].(map[string]interface{})["compute_id"].(int)),
						}

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

	return nil
}

func deleteWGs(ctx context.Context, c *controller.ControllerCfg, cluster *k8s.RecordK8S, deleted []interface{}) error {
	for _, elem := range deleted {
		found_wg := elem.(map[string]interface{})
		req := k8s.WorkersGroupDeleteRequest{
			K8SID:          cluster.ID,
			WorkersGroupID: uint64(found_wg["id"].(int)),
		}

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

func addWGs(ctx context.Context, c *controller.ControllerCfg, cluster *k8s.RecordK8S, added []interface{}) error {
	for _, elem := range added {
		found_wg := elem.(map[string]interface{})
		req := k8s.WorkersGroupAddRequest{
			K8SID:         cluster.ID,
			Name:          found_wg["name"].(string),
			WorkerSEPID:   uint64(found_wg["sep_id"].(int)),
			WorkerSEPPool: found_wg["sep_pool"].(string),
			WorkerNum:     uint64(found_wg["num"].(int)),
			WorkerCPU:     uint64(found_wg["cpu"].(int)),
			WorkerRAM:     uint64(found_wg["ram"].(int)),
			WorkerDisk:    uint64(found_wg["disk"].(int)),
			Chipset:       found_wg["chipset"].(string),
		}

		labels, _ := found_wg["labels"].([]interface{})
		for _, label := range labels {
			if !strings.HasPrefix(label.(string), "workersGroupName") {
				req.Labels = append(req.Labels, label.(string))
			}
		}

		annotations, _ := found_wg["annotations"].([]interface{})
		for _, annotation := range annotations {
			req.Annotations = append(req.Annotations, annotation.(string))
		}

		taints, _ := found_wg["taints"].([]interface{})
		for _, taint := range taints {
			req.Taints = append(req.Taints, taint.(string))
		}

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

	return nil
}

func utilityK8sCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*k8s.RecordK8S, error) {
	c := m.(*controller.ControllerCfg)

	var k8sID uint64
	if d.Id() != "" {
		k8sID, _ = strconv.ParseUint(d.Id(), 10, 64)
	} else {
		k8sID = uint64(d.Get("k8s_id").(int))
	}
	req := k8s.GetRequest{
		K8SID: k8sID,
	}

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

	return k8s, nil
}

func utilityComputeCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}, computeID uint64) (*compute.RecordCompute, error) {
	c := m.(*controller.ControllerCfg)
	req := compute.GetRequest{
		ComputeID: computeID,
	}

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

	return compute, nil
}

func utilityDataK8sCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*k8s.RecordK8S, error) {
	c := m.(*controller.ControllerCfg)

	req := k8s.GetRequest{
		K8SID: uint64(d.Get("k8s_id").(int)),
	}

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

	return k8s, nil
}

func utilityK8sListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*k8s.ListK8SClusters, error) {
	c := m.(*controller.ControllerCfg)
	req := k8s.ListRequest{
		IncludeDeleted: false,
	}

	if by_id, ok := d.GetOk("by_id"); ok {
		req.ByID = uint64(by_id.(int))
	}

	if name, ok := d.GetOk("name"); ok {
		req.Name = name.(string)
	}

	if ip_address, ok := d.GetOk("ip_address"); ok {
		req.IPAddress = ip_address.(string)
	}

	if rg_id, ok := d.GetOk("rg_id"); ok {
		req.RGID = uint64(rg_id.(int))
	}

	if lb_id, ok := d.GetOk("lb_id"); ok {
		req.LBID = uint64(lb_id.(int))
	}

	if bservice_id, ok := d.GetOk("bservice_id"); ok {
		req.BasicServiceID = uint64(bservice_id.(int))
	}

	if status, ok := d.GetOk("status"); ok {
		req.Status = status.(string)
	}

	if tech_status, ok := d.GetOk("tech_status"); ok {
		req.TechStatus = tech_status.(string)
	}

	if includedeleted, ok := d.GetOk("includedeleted"); ok {
		req.IncludeDeleted = includedeleted.(bool)
	}

	if sortBy, ok := d.GetOk("sort_by"); ok {
		req.SortBy = sortBy.(string)
	}

	if page, ok := d.GetOk("page"); ok {
		req.Page = uint64(page.(int))
	}

	if size, ok := d.GetOk("size"); ok {
		req.Size = uint64(size.(int))
	}
	if zoneID, ok := d.GetOk("zone_id"); ok {
		req.ZoneID = uint64(zoneID.(int))
	}

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

	return k8sList, nil
}

func utilityK8sListForResourceCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*k8s.ListK8SClusters, error) {
	c := m.(*controller.ControllerCfg)
	req := k8s.ListRequest{
		IncludeDeleted: false,
	}
	if name, ok := d.GetOk("name"); ok {
		req.Name = name.(string)
	}
	k8sList, err := c.CloudAPI().K8S().List(ctx, req)
	if err != nil {
		return nil, err
	}

	return k8sList, nil
}

func utilityK8sListDeletedCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*k8s.ListK8SClusters, error) {
	c := m.(*controller.ControllerCfg)
	req := k8s.ListDeletedRequest{}

	if by_id, ok := d.GetOk("by_id"); ok {
		req.ByID = uint64(by_id.(int))
	}

	if name, ok := d.GetOk("name"); ok {
		req.Name = name.(string)
	}

	if ip_address, ok := d.GetOk("ip_address"); ok {
		req.IPAddress = ip_address.(string)
	}

	if rg_id, ok := d.GetOk("rg_id"); ok {
		req.RGID = uint64(rg_id.(int))
	}

	if lb_id, ok := d.GetOk("lb_id"); ok {
		req.LBID = uint64(lb_id.(int))
	}

	if bservice_id, ok := d.GetOk("bservice_id"); ok {
		req.BasicServiceID = uint64(bservice_id.(int))
	}

	if tech_status, ok := d.GetOk("tech_status"); ok {
		req.TechStatus = tech_status.(string)
	}

	if sortBy, ok := d.GetOk("sort_by"); ok {
		req.SortBy = sortBy.(string)
	}

	if page, ok := d.GetOk("page"); ok {
		req.Page = uint64(page.(int))
	}

	if size, ok := d.GetOk("size"); ok {
		req.Size = uint64(size.(int))
	}

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

	return k8sList, nil
}

func workersDifference(slice1 []interface{}, slice2 []interface{}) []interface{} {
	var diff []interface{}

	for i := 0; i < 2; i++ {
		for _, s1 := range slice1 {
			found := false
			for _, s2 := range slice2 {
				if s1.(map[string]interface{})["id"] == s2.(map[string]interface{})["id"] {
					found = true
					break
				}
			}

			if !found {
				diff = append(diff, s1)
			}
		}

		if i == 0 {
			slice1, slice2 = slice2, slice1
		}
	}

	return diff
}
