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

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

	log "github.com/sirupsen/logrus"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/account"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/ic"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/status"

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

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

	accountID := d.Get("account_id").(int)

	req := account.GetRequest{}

	if d.Id() == "" {
		req.AccountID = uint64(accountID)
	} else {
		req.AccountID, _ = strconv.ParseUint(d.Id(), 10, 64)
	}

	log.Debugf("utilityAccountCheckPresence: load account")
	account, err := c.CloudBroker().Account().Get(ctx, req)
	if err != nil {
		return nil, err
	}

	return account, nil
}

func utilityAccountEnableUpdate(ctx context.Context, d *schema.ResourceData, m interface{}, acc *account.RecordAccount) error {
	c := m.(*controller.ControllerCfg)

	enable := d.Get("enable").(bool)

	if enable && acc.Status == status.Disabled {
		_, err := c.CloudBroker().Account().Enable(ctx, account.EnableRequest{
			AccountID: acc.ID,
		})

		if err != nil {
			return err
		}
	} else if !enable && acc.Status == status.Confirmed {
		_, err := c.CloudBroker().Account().Disable(ctx, account.DisableRequest{
			AccountID: acc.ID,
		})

		if err != nil {
			return err
		}
	}

	return nil
}

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

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

	cpuAllocationParameter := d.Get("cpu_allocation_parameter").(string)

	_, err := c.CloudBroker().Account().SetCPUAllocationParameter(ctx, account.SetCPUAllocationParameterRequest{
		AccountID:   accountId,
		StrictLoose: cpuAllocationParameter,
	})
	if err != nil {
		return err
	}

	return nil
}

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

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

	cpuAllocacationRatio := d.Get("cpu_allocation_ratio").(float64)

	_, err := c.CloudBroker().Account().SetCPUAllocationRatio(ctx, account.SetCPUAllocationRatioRequest{
		AccountID: accountId,
		Ratio:     cpuAllocacationRatio,
	})
	if err != nil {
		return err
	}

	return nil
}

func utilityAccountUsersUpdate(ctx context.Context, d *schema.ResourceData, m interface{}, acc *account.RecordAccount) error {
	c := m.(*controller.ControllerCfg)

	deletedUsers := make([]interface{}, 0)
	addedUsers := make([]interface{}, 0)
	updatedUsers := make([]interface{}, 0)

	old, new := d.GetChange("users")
	oldConv := old.([]interface{})
	newConv := new.([]interface{})
	for _, el := range oldConv {
		if !isContainsUser(newConv, el) {
			deletedUsers = append(deletedUsers, el)
		}
	}

	for _, el := range newConv {
		if !isContainsUser(oldConv, el) {
			duplicate := false
			for _, user := range acc.ACL {
				if user.UserGroupID == el.(map[string]interface{})["user_id"].(string) {
					duplicate = true
				}
			}
			if !duplicate {
				addedUsers = append(addedUsers, el)
			} else if isChangedUser(oldConv, el) {
				updatedUsers = append(updatedUsers, el)
			}
		}
	}
	for _, user := range deletedUsers {
		userConv := user.(map[string]interface{})

		_, err := c.CloudBroker().Account().DeleteUser(ctx, account.DeleteUserRequest{
			AccountID: acc.ID,
			UserName:  userConv["user_id"].(string),
		})

		if err != nil {
			return err
		}
	}

	for _, user := range addedUsers {
		userConv := user.(map[string]interface{})

		_, err := c.CloudBroker().Account().AddUser(ctx, account.AddUserRequest{
			AccountID:  acc.ID,
			Username:   userConv["user_id"].(string),
			AccessType: strings.ToUpper(userConv["access_type"].(string)),
		})

		if err != nil {
			return err
		}
	}

	for _, user := range updatedUsers {
		userConv := user.(map[string]interface{})

		_, err := c.CloudBroker().Account().UpdateUser(ctx, account.UpdateUserRequest{
			AccountID:  acc.ID,
			UserID:     userConv["user_id"].(string),
			AccessType: strings.ToUpper(userConv["access_type"].(string)),
		})

		if err != nil {
			return err
		}
	}

	return nil
}

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

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

	req := account.UpdateRequest{
		AccountID:        accountId,
		SendAccessEmails: d.Get("send_access_emails").(bool),
	}

	if d.HasChange("account_name") {
		req.Name = d.Get("account_name").(string)
	}

	if d.HasChange("desc") {
		req.Description = d.Get("desc").(string)
	}

	if d.HasChange("default_zone_id") {
		req.DefaultZoneID = uint64(d.Get("default_zone_id").(int))
	}

	if d.HasChange("uniq_pools") {
		uniqPools := d.Get("uniq_pools").([]interface{})

		for _, pool := range uniqPools {
			req.UniqPools = append(req.UniqPools, pool.(string))
		}
	}

	if d.HasChange("resource_limits") {
		resLimit := d.Get("resource_limits").([]interface{})[0]
		resLimitConv := resLimit.(map[string]interface{})

		if resLimitConv["cu_m"] != nil {
			maxMemCap := int(resLimitConv["cu_m"].(float64))
			if maxMemCap == 0 {
				req.MaxMemoryCapacity = -1
			} else {
				req.MaxMemoryCapacity = int64(maxMemCap)
			}
		}
		if resLimitConv["cu_dm"] != nil {
			maxDiskCap := int(resLimitConv["cu_dm"].(float64))
			if maxDiskCap == 0 {
				req.MaxVDiskCapacity = -1
			} else {
				req.MaxVDiskCapacity = int64(maxDiskCap)
			}
		}
		if resLimitConv["cu_c"] != nil {
			maxCPUCap := int(resLimitConv["cu_c"].(float64))
			if maxCPUCap == 0 {
				req.MaxCPUCapacity = -1
			} else {
				req.MaxCPUCapacity = int64(maxCPUCap)
			}
		}
		if resLimitConv["cu_i"] != nil {
			maxNumPublicIP := int(resLimitConv["cu_i"].(float64))
			if maxNumPublicIP == 0 {
				req.MaxNumPublicIP = -1
			} else {
				req.MaxNumPublicIP = int64(maxNumPublicIP)
			}
		}
		if resLimitConv["gpu_units"] != nil {
			gpuUnits := int(resLimitConv["gpu_units"].(float64))
			if gpuUnits == 0 {
				req.GPUUnits = -1
			} else {
				req.GPUUnits = int64(gpuUnits)
			}
		}
	}

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

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

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

	return nil
}

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

	accountId, _ := 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 := account.AddStoragePolicyRequest{
				AccountID:       accountId,
				StoragePolicyID: uint64(spMap["id"].(int)),
				Limit:           spMap["limit"].(int),
			}
			log.Debugf("utilityAccountUpdateStPolicy: starting to add storage policy ID:%d for account %d", req.StoragePolicyID, req.AccountID)
			_, err := c.CloudBroker().Account().AddStoragePolicy(ctx, req)
			if err != nil {
				return needUpdate, err
			}
		}
	}

	if len(delSP) > 0 {
		for _, spMap := range delSP {
			req := account.DelStoragePolicyRequest{
				AccountID:       accountId,
				StoragePolicyID: uint64(spMap["id"].(int)),
			}
			log.Debugf("utilityAccountUpdateStPolicy: starting to delete storage policy ID:%d from account %d", req.StoragePolicyID, req.AccountID)
			_, err := c.CloudBroker().Account().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
}

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

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

	if afterCreate {
		addedAT := d.Get("available_templates").(*schema.Set).List()
		imageIds := make([]uint64, 0, len(addedAT))

		for _, imageId := range addedAT {
			imageIds = append(imageIds, uint64(imageId.(int)))
		}

		if err := ic.ExistImages(ctx, imageIds, c); err != nil {
			return fmt.Errorf("can not grant access for available templates: %w", err)
		}

		req := account.GrantAccessTemplatesRequest{
			AccountID: accountId,
			ImageIDs:  imageIds,
		}

		_, err := c.CloudBroker().Account().GrantAccessTemplates(ctx, req)
		if err != nil {
			return err
		}

		return nil
	}

	oldSet, newSet := d.GetChange("available_templates")

	revokeAT := (oldSet.(*schema.Set).Difference(newSet.(*schema.Set))).List()
	if len(revokeAT) > 0 {
		imageIds := make([]uint64, 0, len(revokeAT))

		for _, imageId := range revokeAT {
			imageIds = append(imageIds, uint64(imageId.(int)))
		}

		if err := ic.ExistImages(ctx, imageIds, c); err != nil {
			return fmt.Errorf("can not revoke access for available templates: %w", err)
		}

		req := account.RevokeAccessTemplatesRequest{
			AccountID: accountId,
			ImageIDs:  imageIds,
		}

		_, err := c.CloudBroker().Account().RevokeAccessTemplates(ctx, req)
		if err != nil {
			return err
		}
	}

	addedAT := (newSet.(*schema.Set).Difference(oldSet.(*schema.Set))).List()
	if len(addedAT) > 0 {
		imageIds := make([]uint64, 0, len(addedAT))

		for _, imageId := range addedAT {
			imageIds = append(imageIds, uint64(imageId.(int)))
		}

		if err := ic.ExistImages(ctx, imageIds, c); err != nil {
			return fmt.Errorf("can not grant access for available templates: %w", err)
		}

		req := account.GrantAccessTemplatesRequest{
			AccountID: accountId,
			ImageIDs:  imageIds,
		}

		_, err := c.CloudBroker().Account().GrantAccessTemplates(ctx, req)
		if err != nil {
			return err
		}
	}

	return nil
}

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

	accountId, _ := strconv.ParseUint(d.Id(), 10, 64)
	compFeaturesInterface := d.Get("compute_features").(*schema.Set).List()

	compFeatures := make([]string, 0, len(compFeaturesInterface))
	for _, item := range compFeaturesInterface {
		compFeatures = append(compFeatures, item.(string))
	}

	req := account.UpdateComputeFeaturesRequest{
		AccountID:       accountId,
		ComputeFeatures: compFeatures,
	}

	_, err := c.CloudBroker().Account().UpdateComputeFeatures(ctx, req)
	if err != nil {
		return err
	}

	return nil
}

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

	accountId, _ := strconv.ParseUint(d.Id(), 10, 64)
	zones := toUpdate.List()

	compZones := make([]uint64, 0, len(zones))
	for _, item := range zones {
		compZones = append(compZones, uint64(item.(int)))

	}

	req := account.AddZoneRequest{
		AccountID: accountId,
		ZoneIDs:   compZones,
	}

	_, err := c.CloudBroker().Account().AddZone(ctx, req)
	if err != nil {
		return err
	}

	return nil
}

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

	accountId, _ := strconv.ParseUint(d.Id(), 10, 64)
	zones := toRemove.List()

	compZones := make([]uint64, 0, len(zones))
	for _, item := range zones {
		compZones = append(compZones, uint64(item.(int)))

	}

	req := account.RemoveZoneRequest{
		AccountID: accountId,
		ZoneIDs:   compZones,
	}

	_, err := c.CloudBroker().Account().RemoveZone(ctx, req)
	if err != nil {
		return err
	}

	return nil
}

func isContainsUser(els []interface{}, el interface{}) bool {
	for _, elOld := range els {
		elOldConv := elOld.(map[string]interface{})
		elConv := el.(map[string]interface{})
		if elOldConv["user_id"].(string) == elConv["user_id"].(string) {
			return true
		}
	}
	return false
}

func isChangedUser(els []interface{}, el interface{}) bool {
	for _, elOld := range els {
		elOldConv := elOld.(map[string]interface{})
		elConv := el.(map[string]interface{})
		if elOldConv["user_id"].(string) == elConv["user_id"].(string) &&
			(!strings.EqualFold(elOldConv["access_type"].(string), elConv["access_type"].(string))) {
			return true
		}
	}
	return false
}
