/*
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 (
	"encoding/json"

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

func flattenRGSeps(seps map[string]map[string]rg.DiskUsage) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	for sepKey, sepVal := range seps {
		for dataKey, dataVal := range sepVal {
			temp := map[string]interface{}{
				"sep_id":        sepKey,
				"data_name":     dataKey,
				"disk_size":     dataVal.DiskSize,
				"disk_size_max": dataVal.DiskSizeMax,
			}
			res = append(res, temp)
		}
	}

	return res
}

// func flattenAccResource(r Resource) []map[string]interface{} {
// 	res := make([]map[string]interface{}, 0)
// 	temp := map[string]interface{}{
// 		"cpu":        r.CPU,
// 		"disksize":   r.DiskSize,
// 		"extips":     r.ExtIPs,
// 		"gpu":        r.GPU,
// 		"ram":        r.RAM,
// 		"seps":       flattenRgSeps(r.SEPs),
// 	}
// 	res = append(res, temp)

// 	return res
// }

// func flattenRgResources(r Resources) []map[string]interface{} {
// 	res := make([]map[string]interface{}, 0)
// 	temp := map[string]interface{}{
// 		"current":  flattenAccResource(r.Current),
// 		"reserved": flattenAccResource(r.Reserved),
// 	}
// 	res = append(res, temp)
// 	return res
// }

func flattenResgroup(d *schema.ResourceData, details rg.RecordResourceGroup) error {
	log.Debugf("flattenResgroup: decoded RG name %q / ID %d, account ID %d",
		details.Name, details.ID, details.AccountID)

	d.Set("account_id", details.AccountID)
	d.Set("gid", details.GID)
	d.Set("name", details.Name)
	d.Set("quota", flattenQuota(details.ResourceLimits))
	d.Set("account_name", details.AccountName)
	d.Set("acl", flattenRgAcl(details.ACL))
	d.Set("compute_features", details.ComputeFeatures)
	d.Set("storage_policy", flattenRgStoragePolicy(details.ResourceLimits.StoragePolicies))
	d.Set("vms", details.Computes)
	d.Set("created_by", details.CreatedBy)
	d.Set("created_time", details.CreatedTime)
	d.Set("def_net_id", details.DefNetID)
	d.Set("deleted_by", details.DeletedBy)
	d.Set("deleted_time", details.DeletedTime)
	d.Set("description", details.Description)
	d.Set("dirty", details.Dirty)
	d.Set("guid", details.GUID)
	d.Set("rg_id", details.ID)
	d.Set("lock_status", details.LockStatus)
	d.Set("milestones", details.Milestones)
	d.Set("res_types", details.ResTypes)
	d.Set("secret", details.Secret)
	d.Set("status", details.Status)
	d.Set("updated_by", details.UpdatedBy)
	d.Set("updated_time", details.UpdatedTime)
	d.Set("uniq_pools", details.UniqPools)
	d.Set("vins", details.VINS)
	d.Set("cpu_allocation_parameter", details.CPUAllocationParameter)
	d.Set("cpu_allocation_ratio", details.CPUAllocationRatio)
	d.Set("sdn_access_group_id", details.SDNAccessGroupID)
	d.Set("resource_limits", flattenRgResourceLimits(details.ResourceLimits))
	d.Set("storage_policy_ids", details.StoragePolicyIDs)

	return nil
}

func flattenRgSeps(seps map[string]map[string]rg.DiskUsage) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(seps))
	for sepKey, sepVal := range seps {
		SepMap := map[string]interface{}{}
		for dataKey, dataVal := range sepVal {
			val, _ := json.Marshal(dataVal)
			SepMap[dataKey] = string(val)
		}
		temp := map[string]interface{}{
			"sep_id": sepKey,
			"map":    SepMap,
		}
		res = append(res, temp)
	}
	return res
}

func flattenQuota(resource rg.ResourceLimits) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	temp := map[string]interface{}{
		"cpu":       resource.CUC,
		"ram":       resource.CUM,
		"disk":      resource.CUDM,
		"ext_ips":   resource.CUI,
		"gpu_units": resource.GPUUnits,
		"cu_d":      resource.CUD,
	}

	res = append(res, temp)

	return res
}

func flattenResource(resource rg.Resource) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	temp := map[string]interface{}{
		"cpu":           resource.CPU,
		"disk_size":     resource.DiskSize,
		"disk_size_max": resource.DiskSizeMax,
		"extips":        resource.ExtIPs,
		"gpu":           resource.GPU,
		"ram":           resource.RAM,
		"seps":          flattenRGSeps(resource.SEPs),
	}

	res = append(res, temp)

	return res
}

func flattenRg(d *schema.ResourceData, itemRg rg.RecordResourceGroup) {
	// d.Set("resources", flattenRgResource(itemRg.Resources))
	d.Set("account_id", itemRg.AccountID)
	d.Set("account_name", itemRg.AccountName)
	d.Set("acl", flattenRgAcl(itemRg.ACL))
	d.Set("computes", itemRg.Computes)
	d.Set("compute_features", itemRg.ComputeFeatures)
	d.Set("created_by", itemRg.CreatedBy)
	d.Set("created_time", itemRg.CreatedTime)
	d.Set("def_net_id", itemRg.DefNetID)
	d.Set("def_net_type", itemRg.DefNetType)
	d.Set("deleted_by", itemRg.DeletedBy)
	d.Set("deleted_time", itemRg.DeletedTime)
	d.Set("desc", itemRg.Description)
	d.Set("dirty", itemRg.Dirty)
	d.Set("gid", itemRg.GID)
	d.Set("guid", itemRg.GUID)
	d.Set("rg_id", itemRg.ID)
	d.Set("lock_status", itemRg.LockStatus)
	d.Set("milestones", itemRg.Milestones)
	d.Set("name", itemRg.Name)
	d.Set("res_types", itemRg.ResTypes)
	d.Set("resource_limits", flattenRgResourceLimits(itemRg.ResourceLimits))
	d.Set("secret", itemRg.Secret)
	d.Set("status", itemRg.Status)
	d.Set("updated_by", itemRg.UpdatedBy)
	d.Set("updated_time", itemRg.UpdatedTime)
	d.Set("uniq_pools", itemRg.UniqPools)
	d.Set("vins", itemRg.VINS)
	d.Set("cpu_allocation_parameter", itemRg.CPUAllocationParameter)
	d.Set("cpu_allocation_ratio", itemRg.CPUAllocationRatio)
	d.Set("sdn_access_group_id", itemRg.SDNAccessGroupID)
	d.Set("storage_policy_ids", itemRg.StoragePolicyIDs)
}

func flattenRgAudits(rgAudits rg.ListAudits) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(rgAudits))
	for _, rgAudit := range rgAudits {
		temp := map[string]interface{}{
			"call":         rgAudit.Call,
			"responsetime": rgAudit.ResponseTime,
			"statuscode":   rgAudit.StatusCode,
			"timestamp":    rgAudit.Timestamp,
			"user":         rgAudit.User,
		}

		res = append(res, temp)
	}

	return res
}

func flattenRgList(rgl *rg.ListResourceGroups) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(rgl.Data))
	for _, rg := range rgl.Data {
		temp := map[string]interface{}{
			"account_acl":              flattenRgAcl(rg.ACL),
			"account_id":               rg.AccountID,
			"account_name":             rg.AccountName,
			"compute_features":         rg.ComputeFeatures,
			"created_by":               rg.CreatedBy,
			"created_time":             rg.CreatedTime,
			"def_net_id":               rg.DefNetID,
			"def_net_type":             rg.DefNetType,
			"deleted_by":               rg.DeletedBy,
			"deleted_time":             rg.DeletedTime,
			"desc":                     rg.Description,
			"dirty":                    rg.Dirty,
			"gid":                      rg.GID,
			"guid":                     rg.GUID,
			"rg_id":                    rg.ID,
			"lock_status":              rg.LockStatus,
			"milestones":               rg.Milestones,
			"name":                     rg.Name,
			"resource_limits":          flattenRgResourceLimits(rg.ResourceLimits),
			"secret":                   rg.Secret,
			"status":                   rg.Status,
			"updated_by":               rg.UpdatedBy,
			"updated_time":             rg.UpdatedTime,
			"vins":                     rg.VINS,
			"vms":                      rg.Computes,
			"resource_types":           rg.ResTypes,
			"uniq_pools":               rg.UniqPools,
			"cpu_allocation_parameter": rg.CPUAllocationParameter,
			"cpu_allocation_ratio":     rg.CPUAllocationRatio,
			"sdn_access_group_id":      rg.SDNAccessGroupID,
			"storage_policy_ids":       rg.StoragePolicyIDs,
		}
		res = append(res, temp)
	}
	return res
}

func flattenRgAcl(rgAcls rg.ListACL) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(rgAcls))
	for _, rgAcl := range rgAcls {
		temp := map[string]interface{}{
			"email":         rgAcl.Email,
			"explicit":      rgAcl.Explicit,
			"guid":          rgAcl.GUID,
			"right":         rgAcl.Right,
			"status":        rgAcl.Status,
			"type":          rgAcl.Type,
			"user_group_id": rgAcl.UserGroupID,
		}
		res = append(res, temp)
	}
	return res
}

func flattenRgResourceLimits(rl rg.ResourceLimits) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	temp := map[string]interface{}{
		"cu_c":           rl.CUC,
		"cu_d":           rl.CUD,
		"cu_i":           rl.CUI,
		"cu_m":           rl.CUM,
		"cu_dm":          rl.CUDM,
		"gpu_units":      rl.GPUUnits,
		"storage_policy": flattenRgStoragePolicy(rl.StoragePolicies),
	}
	res = append(res, temp)

	return res
}

func flattenRgStoragePolicy(spList []rg.StoragePolicy) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(spList))
	for _, sp := range spList {
		temp := map[string]interface{}{
			"id":    sp.ID,
			"limit": sp.Limit,
		}

		res = append(res, temp)
	}

	return res
}

func flattenRules(list rg.ListRules) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(list))
	for _, rule := range list {
		temp := map[string]interface{}{
			"guid":     rule.GUID,
			"key":      rule.Key,
			"mode":     rule.Mode,
			"policy":   rule.Policy,
			"topology": rule.Topology,
			"value":    rule.Value,
		}

		res = append(res, temp)
	}

	return res
}

func flattenRgListComputes(lc *rg.ListComputes) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(lc.Data))
	for _, compute := range lc.Data {
		temp := map[string]interface{}{
			"account_id":         compute.AccountID,
			"account_name":       compute.AccountName,
			"affinity_label":     compute.AffinityLabel,
			"affinity_rules":     flattenRules(compute.AffinityRules),
			"affinity_weight":    compute.AffinityWeight,
			"antiaffinity_rules": flattenRules(compute.AntiAffinityRules),
			"cpus":               compute.CPUs,
			"created_by":         compute.CreatedBy,
			"created_time":       compute.CreatedTime,
			"deleted_by":         compute.DeletedBy,
			"deleted_time":       compute.DeletedTime,
			"id":                 compute.ID,
			"name":               compute.Name,
			"ram":                compute.RAM,
			"registered":         compute.Registered,
			"rg_name":            compute.RGName,
			"status":             compute.Status,
			"tech_status":        compute.TechStatus,
			"total_disks_size":   compute.TotalDisksSize,
			"updated_by":         compute.UpdatedBy,
			"updated_time":       compute.UpdatedTime,
			"user_managed":       compute.UserManaged,
			"vins_connected":     compute.VINSConnected,
		}

		res = append(res, temp)
	}

	return res
}

func flattenServerSettings(settings rg.RecordServerSettings) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	temp := map[string]interface{}{
		"inter":      settings.Inter,
		"guid":       settings.GUID,
		"down_inter": settings.DownInter,
		"rise":       settings.Rise,
		"fall":       settings.Fall,
		"slow_start": settings.SlowStart,
		"max_conn":   settings.MaxConn,
		"max_queue":  settings.MaxQueue,
		"weight":     settings.Weight,
	}
	res = append(res, temp)
	return res
}

func flattenListServers(list rg.ListServers) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(list))
	for _, serv := range list {
		temp := map[string]interface{}{
			"address":         serv.Address,
			"check":           serv.Check,
			"guid":            serv.GUID,
			"name":            serv.Name,
			"port":            serv.Port,
			"server_settings": flattenServerSettings(serv.ServerSettings),
		}
		res = append(res, temp)
	}

	return res
}

func flattenBackends(b rg.ListBackends) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(b))
	for _, item := range b {
		temp := map[string]interface{}{
			"algorithm":               item.Algorithm,
			"guid":                    item.GUID,
			"name":                    item.Name,
			"server_default_settings": flattenServerSettings(item.ServerDefaultSettings),
			"servers":                 flattenListServers(item.Servers),
		}
		res = append(res, temp)
	}
	return res
}

func flattenBindings(list rg.ListBindings) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(list))
	for _, bind := range list {
		temp := map[string]interface{}{
			"address": bind.Address,
			"guid":    bind.GUID,
			"name":    bind.Name,
			"port":    bind.Port,
		}
		res = append(res, temp)
	}

	return res
}

func flattenFrontends(list rg.ListFrontends) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(list))
	for _, front := range list {
		temp := map[string]interface{}{
			"backend":  front.Backend,
			"bindings": flattenBindings(front.Bindings),
			"guid":     front.GUID,
			"name":     front.Name,
		}
		res = append(res, temp)
	}

	return res
}

func flattenNode(node rg.RecordNode) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	temp := map[string]interface{}{
		"backend_ip":  node.BackendIP,
		"compute_id":  node.ComputeID,
		"frontend_ip": node.FrontendIP,
		"guid":        node.GUID,
		"mgmt_ip":     node.MGMTIP,
		"network_id":  node.NetworkID,
	}
	res = append(res, temp)
	return res
}

func flattenRgListLb(listLb *rg.ListLB) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(listLb.Data))
	for _, lb := range listLb.Data {
		temp := map[string]interface{}{
			"ha_mode":        lb.HAMode,
			"acl":            lb.ACL,
			"backend_haip":   lb.BackendHAIP,
			"backends":       flattenBackends(lb.Backends),
			"created_by":     lb.CreatedBy,
			"created_time":   lb.CreatedTime,
			"deleted_by":     lb.DeletedBy,
			"deleted_time":   lb.DeletedTime,
			"desc":           lb.Description,
			"dp_api_user":    lb.DPAPIUser,
			"extnet_id":      lb.ExtNetID,
			"frontend_haip":  lb.FrontendHAIP,
			"frontends":      flattenFrontends(lb.Frontends),
			"gid":            lb.GID,
			"guid":           lb.GUID,
			"id":             lb.ID,
			"image_id":       lb.ImageID,
			"milestones":     lb.Milestones,
			"name":           lb.Name,
			"primary_node":   flattenNode(lb.PrimaryNode),
			"rg_name":        lb.RGName,
			"secondary_node": flattenNode(lb.SecondaryNode),
			"status":         lb.Status,
			"tech_status":    lb.TechStatus,
			"updated_by":     lb.UpdatedBy,
			"updated_time":   lb.UpdatedTime,
			"vins_id":        lb.VINSID,
		}
		res = append(res, temp)
	}
	return res
}

func flattenRgListPfw(listPfw *rg.ListPortForwards) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(listPfw.Data))
	for _, pfw := range listPfw.Data {
		temp := map[string]interface{}{
			"public_port_end":   pfw.PublicPortEnd,
			"public_port_start": pfw.PublicPortStart,
			"vm_id":             pfw.VMID,
			"vm_ip":             pfw.VMIP,
			"vm_name":           pfw.VMName,
			"vm_port":           pfw.VMPort,
			"vins_id":           pfw.VINSID,
			"vins_name":         pfw.VINSName,
		}
		res = append(res, temp)
	}

	return res
}

func flattenRgListVins(lv *rg.ListVINS) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(lv.Data))
	for _, vins := range lv.Data {
		temp := map[string]interface{}{
			"account_id":     vins.AccountID,
			"account_name":   vins.AccountName,
			"computes":       vins.Computes,
			"created_by":     vins.CreatedBy,
			"created_time":   vins.CreatedTime,
			"deleted_by":     vins.DeletedBy,
			"deleted_time":   vins.DeletedTime,
			"external_ip":    vins.ExternalIP,
			"extnet_id":      vins.ExtnetId,
			"free_ips":       vins.FreeIPs,
			"id":             vins.ID,
			"name":           vins.Name,
			"network":        vins.Network,
			"pri_vnf_dev_id": vins.PriVNFDevID,
			"rg_name":        vins.RGName,
			"status":         vins.Status,
			"updated_by":     vins.UpdatedBy,
			"updated_time":   vins.UpdatedTime,
		}

		res = append(res, temp)
	}

	return res
}

func flattenRgAffinityGroupComputes(list rg.ListAffinityGroupsComputes) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(list))

	for _, item := range list {
		temp := map[string]interface{}{
			"compute_id":               item.ComputeID,
			"other_node":               item.OtherNode,
			"other_node_indirect":      item.OtherNodeIndirect,
			"other_node_indirect_soft": item.OtherNodeIndirectSoft,
			"other_node_soft":          item.OtherNodeSoft,
			"same_node":                item.SameNode,
			"same_node_soft":           item.SameNodeSoft,
		}
		res = append(res, temp)
	}

	return res
}

// func flattenRgAffinityGroupsGet(list []uint64) []map[string]interface{} {
// 	res := make([]map[string]interface{}, 0)
// 	temp := map[string]interface{}{
// 		"items": list,
// 	}
// 	res = append(res, temp)

// 	return res
// }

func flattenRgListGroups(list *rg.ListAffinityGroups) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(list.Data))
	for _, groupVal := range list.Data {
		for label, ag := range groupVal {
			temp := map[string]interface{}{
				"label": label,
				"ids":   flattenRgAffinityListGroup(ag),
			}
			res = append(res, temp)
		}
	}

	return res
}

func flattenRgAffinityListGroup(list rg.ListAffinityGroup) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(list))
	for _, ag := range list {
		temp := map[string]interface{}{
			"id":      ag.ID,
			"node_id": ag.NodeID,
		}
		res = append(res, temp)
	}

	return res
}

func flattenRgUsageResource(d *schema.ResourceData, usage rg.RecordResourceUsage) {
	d.Set("cpu", usage.CPU)
	d.Set("disk_size", usage.DiskSize)
	d.Set("disk_size_max", usage.DiskSizeMax)
	d.Set("extips", usage.ExtIPs)
	d.Set("gpu", usage.GPU)
	d.Set("ram", usage.RAM)
	d.Set("seps", flattenRgSeps(usage.SEPs))
}

func flattenRGResourceConsumptionList(rg *rg.ListResourceConsumption) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(rg.Data))
	for _, rc := range rg.Data {
		temp := map[string]interface{}{
			"consumed":        flattenResource(rc.Consumed),
			"reserved":        flattenResource(rc.Reserved),
			"resource_limits": flattenRgResourceLimits(rc.ResourceLimits),
			"rg_id":           rc.RGID,
		}
		res = append(res, temp)
	}
	return res
}

func flattenRGResourceConsumption(d *schema.ResourceData, rg *rg.ItemResourceConsumption) {
	d.Set("consumed", flattenResource(rg.Consumed))
	d.Set("reserved", flattenResource(rg.Reserved))
	d.Set("resource_limits", flattenRgResourceLimits(rg.ResourceLimits))
	d.Set("rg_id", rg.RGID)
}
