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

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/cloudbroker/rg"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
)

func utilityResgroupCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*rg.RecordRG, 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.CloudBroker().RG().Get(ctx, req)
	if err != nil {
		return nil, err
	}

	return rgData, nil
}

func utilityRGUpdateStPolicy(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, []map[string]interface{}, 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 rg %d", req.StoragePolicyID, req.RGID)
			_, err := c.CloudBroker().RG().AddStoragePolicy(ctx, req)
			if err != nil {
				return needUpdate, updateSP, 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 rg %d", req.StoragePolicyID, req.RGID)
			_, err := c.CloudBroker().RG().DelStoragePolicy(ctx, req)
			if err != nil {
				return needUpdate, updateSP, err
			}
		}
	}

	return needUpdate, updateSP, 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
}
