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

import (
	"context"
	"fmt"
	"strconv"

	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/vfpool"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/ic"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
	log "github.com/sirupsen/logrus"
)

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

	if d.Id() != "" {
		vfpoolId, _ := strconv.ParseUint(d.Id(), 10, 64)
		req.VFPoolID = vfpoolId
	} else {
		req.VFPoolID = uint64(d.Get("vfpool_id").(int))
	}

	vfpoolData, err := c.CloudBroker().VFPool().Get(ctx, req)
	if err != nil {
		return nil, err
	}

	return vfpoolData, nil
}

func utilityVFPoolEnabled(ctx context.Context, m interface{}, enable bool, vfPoolID uint64) error {
	c := m.(*controller.ControllerCfg)

	var err error

	if enable {
		_, err = c.CloudBroker().VFPool().Enable(ctx, vfpool.EnableRequest{VFPoolID: vfPoolID})
	} else {
		_, err = c.CloudBroker().VFPool().Disable(ctx, vfpool.DisableRequest{VFPoolID: vfPoolID})
	}

	return err
}

func utilityVFPoolUpdate(ctx context.Context, d *schema.ResourceData, m interface{}, vfPoolID uint64) error {
	hasConfig := len(d.Get("config").(*schema.Set).List()) > 0
	if d.Get("enable").(bool) && !hasConfig {
		return fmt.Errorf("enable requires config to be set")
	}

	c := m.(*controller.ControllerCfg)

	vfPool, err := utilityVFpoolCheckPresence(ctx, d, m)
	if err != nil {
		d.SetId("")
		return err
	}

	req := vfpool.UpdateRequest{
		VFPoolID: vfPoolID,
	}

	if d.HasChange("name") {
		req.Name = d.Get("name").(string)
	}
	if d.HasChange("description") {
		req.Description = d.Get("description").(string)
	}

	if config, ok := d.GetOk("config"); ok {
		configArray := config.(*schema.Set).List()
		req.Config = make([]vfpool.Config, 0, len(configArray))

		for _, access := range configArray {
			temp := access.(map[string]interface{})

			vfArray := temp["vf_ids"].([]interface{})
			resVfIds := make([]uint64, 0, len(vfArray))

			for _, vfID := range vfArray {
				resVfIds = append(resVfIds, uint64(vfID.(int)))
			}

			reqTemp := vfpool.Config{
				NodeID:  uint64(temp["node_id"].(int)),
				NicName: temp["nic_name"].(string),
				VFIDs:   resVfIds,
			}
			req.Config = append(req.Config, reqTemp)
		}
	} else {
		req.Config = []vfpool.Config{}
	}

	if accountAccess, ok := d.GetOk("account_access"); ok {
		accountAccessArray := accountAccess.(*schema.Set).List()

		req.AccountAccess = make([]uint64, 0, len(accountAccessArray))

		for _, access := range accountAccessArray {
			req.AccountAccess = append(req.AccountAccess, uint64(access.(int)))
		}

		if err := ic.ExistAccouts(ctx, req.AccountAccess, c); err != nil {
			return err
		}
	} else {
		req.AccountAccess = []uint64{}
	}

	if rgAccess, ok := d.GetOk("rg_access"); ok {
		rgAccessArray := rgAccess.(*schema.Set).List()

		req.RGAccess = make([]uint64, 0, len(rgAccessArray))

		for _, access := range rgAccessArray {
			req.RGAccess = append(req.RGAccess, uint64(access.(int)))
		}

		if err := ic.ExistRGs(ctx, req.RGAccess, c); err != nil {
			return err
		}
	} else {
		req.RGAccess = []uint64{}
	}

	if vfPool.Status == "ENABLED" || vfPool.Status == "CREATED" {
		reqDisable := vfpool.DisableRequest{
			VFPoolID: vfPoolID,
		}

		log.Debugf("utilityVFPoolUpdate: need to disable vfPool with ID: %d, after update", vfPoolID)
		_, err = c.CloudBroker().VFPool().Disable(ctx, reqDisable)
		if err != nil {
			return err
		}
		log.Debugf("utilityVFPoolUpdate: disable vfPool with ID: %d, complete", vfPoolID)
	}

	_, err = c.CloudBroker().VFPool().Update(ctx, req)
	if err != nil {
		return err
	}
	log.Debugf("utilityVFPoolUpdate: update vfPool with ID: %d, complete with params=%v", vfPoolID, req)

	if hasConfig && d.Get("enable").(bool) {
		reqEnable := vfpool.EnableRequest{
			VFPoolID: vfPoolID,
		}

		log.Debugf("utilityVFPoolUpdate: start to enable vfPool with ID: %d, after update", vfPoolID)
		_, err = c.CloudBroker().VFPool().Enable(ctx, reqEnable)
		if err != nil {
			return err
		}
		log.Debugf("utilityVFPoolUpdate: enable vfPool with ID: %d, complete", vfPoolID)
	}

	return nil
}
