/*
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 rg

import (
	"context"
	"strconv"

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

func utilityResgroupCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*rg.RecordResourceGroup, error) {
	c := m.(*controller.ControllerCfg)
	req := rg.GetRequest{}

	if d.Id() != "" {
		rgId, _ := strconv.ParseUint(d.Id(), 10, 64)
		req.RGID = rgId
	} else {
		req.RGID = uint64(d.Get("rg_id").(int))
	}

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

	return rgData, nil
}

func utilityUpdateRG(ctx context.Context, d *schema.ResourceData, m interface{}, rgId uint64) error {
	c := m.(*controller.ControllerCfg)

	req := rg.UpdateRequest{
		RGID: rgId,
	}

	if d.HasChange("name") {
		log.Debugf("resourceResgroupUpdate: name specified - looking for deltas from the old settings")
		req.Name = d.Get("name").(string)
	}

	if d.HasChange("quota") {
		log.Debugf("resourceResgroupUpdate: quota specified - looking for deltas from the old quota.")

		if quota, ok := d.GetOk("quota"); ok {
			resLimits := quota.([]interface{})[0]
			resLimitsConv := resLimits.(map[string]interface{})

			if resLimitsConv["ram"] != nil {
				maxMemCap := int64(resLimitsConv["ram"].(int))
				if maxMemCap == 0 {
					req.MaxMemoryCapacity = -1
				} else {
					req.MaxMemoryCapacity = maxMemCap
				}
			}

			if resLimitsConv["disk"] != nil {
				maxDiskCap := int64(resLimitsConv["disk"].(int))
				if maxDiskCap == 0 {
					req.MaxVDiskCapacity = -1
				} else {
					req.MaxVDiskCapacity = maxDiskCap
				}
			}
			if resLimitsConv["cpu"] != nil {
				maxCPUCap := int64(resLimitsConv["cpu"].(int))
				if maxCPUCap == 0 {
					req.MaxCPUCapacity = -1
				} else {
					req.MaxCPUCapacity = maxCPUCap
				}
			}
			if resLimitsConv["ext_ips"] != nil {
				maxNumPublicIP := int64(resLimitsConv["ext_ips"].(int))
				if maxNumPublicIP == 0 {
					req.MaxNumPublicIP = -1
				} else {
					req.MaxNumPublicIP = maxNumPublicIP
				}
			}
		}
	}

	if d.HasChange("storage_policy") {
		log.Debugf("resourceResgroupUpdate: storage policies specified.")

		if storagePolicies, ok := d.GetOk("storage_policy"); ok {
			var id uint64
			var limit int

			if storagePolicies.(*schema.Set).Len() > 0 {
				spList := storagePolicies.(*schema.Set).List()
				for _, spInterface := range spList {
					sps := spInterface.(map[string]interface{})
					id = uint64(sps["id"].(int))
					limit = sps["limit"].(int)

					spModel := rg.StoragePolicy{
						ID:    id,
						Limit: limit,
					}

					req.StoragePolicies = append(req.StoragePolicies, spModel)
				}
			}
		}
	}

	if d.HasChange("description") {
		log.Debugf("resourceResgroupUpdate: description specified - looking for deltas from the old settings.")
		req.Description = d.Get("description").(string)
	}

	if d.HasChange("uniq_pools") {
		uniqPools := d.Get("uniq_pools").([]interface{})
		if len(uniqPools) == 0 {
			req.ClearUniqPools = true
		}
		for _, pool := range uniqPools {
			req.UniqPools = append(req.UniqPools, pool.(string))
		}
	}

	_, _, updateStPolicy := utilityGetStoragePolicyUpdate(ctx, d, m)
	if len(updateStPolicy) != 0 {
		storagePolicies := make([]rg.StoragePolicy, 0, len(updateStPolicy))
		for _, stPolicyVal := range updateStPolicy {
			reqStPolicy := rg.StoragePolicy{
				ID:    uint64(stPolicyVal["id"].(int)),
				Limit: stPolicyVal["limit"].(int),
			}

			storagePolicies = append(storagePolicies, reqStPolicy)
		}
		req.StoragePolicies = storagePolicies
	}

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

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

	rgID, _ := strconv.ParseUint(d.Id(), 10, 64)

	addSP, delSP, updateSP := utilityGetStoragePolicyUpdate(ctx, d, m)
	needUpdate := len(updateSP) > 0

	if len(addSP) > 0 {
		for _, spMap := range addSP {
			req := rg.AddStoragePolicyRequest{
				RGID:            rgID,
				StoragePolicyID: uint64(spMap["id"].(int)),
				Limit:           spMap["limit"].(int),
			}
			log.Debugf("utilityRGUpdateStPolicy: starting to add storage policy ID:%d for resource group %d", req.StoragePolicyID, req.RGID)
			_, err := c.CloudAPI().RG().AddStoragePolicy(ctx, req)
			if err != nil {
				return needUpdate, err
			}
		}
	}

	if len(delSP) > 0 {
		for _, spMap := range delSP {
			req := rg.DelStoragePolicyRequest{
				RGID:            rgID,
				StoragePolicyID: uint64(spMap["id"].(int)),
			}
			log.Debugf("utilityRGUpdateStPolicy: starting to delete storage policy ID:%d from resource group %d", req.StoragePolicyID, req.RGID)
			_, err := c.CloudAPI().RG().DelStoragePolicy(ctx, req)
			if err != nil {
				return needUpdate, err
			}
		}
	}

	return needUpdate, nil
}

func utilityGetStoragePolicyUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) (added, deleted, updated []map[string]interface{}) {
	added = make([]map[string]interface{}, 0)
	deleted = make([]map[string]interface{}, 0)
	updated = make([]map[string]interface{}, 0)
	oldSet, newSet := d.GetChange("storage_policy")
	oldList := oldSet.(*schema.Set).List()
	newList := newSet.(*schema.Set).List()

	for _, oldSP := range oldList {
		oldMap := oldSP.(map[string]interface{})
		found := false
		for _, newSP := range newList {
			newMap := newSP.(map[string]interface{})
			if oldMap["id"] == newMap["id"] {
				found = true
				if oldMap["limit"] != newMap["limit"] {
					updated = append(added, newMap)
				}
				break
			}
			if found {
				break
			}
		}
		if found {
			continue
		}
		deleted = append(deleted, oldMap)
	}

	for _, newSP := range newList {
		newMap := newSP.(map[string]interface{})
		found := false
		for _, oldSP := range oldList {
			oldMap := oldSP.(map[string]interface{})
			if oldMap["id"] == newMap["id"] {
				found = true
				break
			}
		}
		if found {
			continue
		}
		added = append(added, newMap)
	}

	return
}
