/*
Copyright (c) 2019-2023 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>
Tim Tkachev, <tvtkachev@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 extnet

import (
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/extnet"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/flattens"
)

func flattenListExtnet(extList *extnet.ListExtNet) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	for _, item := range extList.Data {
		temp := map[string]interface{}{
			"ckey":                 item.CKey,
			"meta":                 flattens.FlattenMeta(item.Meta),
			"default":              item.Default,
			"default_qos":          flattenExtnetDefaultQos(item.DefaultQOS),
			"desc":                 item.Description,
			"free_ips":             item.FreeIPs,
			"gid":                  item.GID,
			"guid":                 item.GUID,
			"enable_secgroups":     item.EnableSecGroups,
			"extnet_id":            item.ID,
			"ipcidr":               item.IPCIDR,
			"milestones":           item.Milestones,
			"name":                 item.Name,
			"network_ids":          flattenNetworkIDs(item.NetworkIDs),
			"ovs_bridge":           item.OVSBridge,
			"pre_reservations_num": item.PreReservationsNum,
			"pri_vnfdev_id":        item.PriVNFDevID,
			"shared_with":          item.SharedWith,
			"status":               item.Status,
			"vlan_id":              item.VLANID,
			"check_ips":            item.CheckIPs,
			"vnfs":                 flattenExtnetVNFS(item.VNFs),
			"zone_id":              item.ZoneID,
			"sec_vnfdev_id":        item.SecVNFDevID,
			"redundant":            item.Redundant,
			"mtu":                  item.MTU,
		}

		res = append(res, temp)
	}

	return res
}

func flattenRecordExtnet(d *schema.ResourceData, recNet *extnet.RecordExtNet) {
	d.Set("ckey", recNet.CKey)
	d.Set("meta", flattens.FlattenMeta(recNet.Meta))
	d.Set("default", recNet.Default)
	d.Set("desc", recNet.Description)
	d.Set("free_ips", recNet.FreeIPs)
	d.Set("gid", recNet.GID)
	d.Set("guid", recNet.GUID)
	d.Set("extnet_id", recNet.ID)
	d.Set("ipcidr", recNet.IPCIDR)
	d.Set("milestones", recNet.Milestones)
	d.Set("name", recNet.Name)
	d.Set("network_ids", recNet.NetworkIDs)
	d.Set("ntp", recNet.NTP)
	d.Set("ovs_bridge", recNet.OVSBridge)
	d.Set("pre_reservations_num", recNet.PreReservationsNum)
	d.Set("pri_vnfdev_id", recNet.PriVNFDevID)
	d.Set("shared_with", recNet.SharedWith)
	d.Set("status", recNet.Status)
	d.Set("vlan_id", recNet.VLANID)
	d.Set("check_ips", recNet.CheckIPs)
	d.Set("dns", recNet.DNS)
	d.Set("excluded", flattenExtnetExcluded(recNet.Excluded))
	d.Set("gateway", recNet.Gateway)
	d.Set("network", recNet.Network)
	d.Set("prefix", recNet.Prefix)
	d.Set("default_qos", flattenExtnetDefaultQos(recNet.DefaultQOS))
	d.Set("vnfs", flattenExtnetVNFS(recNet.VNFs))
	d.Set("reservations", flattenExtnetReservations(recNet.Reservations))
	d.Set("zone_id", recNet.ZoneID)
	d.Set("pre_reservations", flattenExtnetReservations(recNet.PreReservations))
	d.Set("sec_vnfdev_id", recNet.SecVNFDevID)
	d.Set("redundant", recNet.Redundant)
	d.Set("mtu", recNet.MTU)
}

func flattenRecordExtnetResource(d *schema.ResourceData, recNet *extnet.RecordExtNet, staticRouteList *extnet.ListStaticRoutes) {
	d.Set("ckey", recNet.CKey)
	d.Set("meta", flattens.FlattenMeta(recNet.Meta))
	d.Set("default", recNet.Default)
	d.Set("desc", recNet.Description)
	d.Set("free_ips", recNet.FreeIPs)
	d.Set("gid", recNet.GID)
	d.Set("guid", recNet.GUID)
	d.Set("extnet_id", recNet.ID)
	d.Set("ipcidr", recNet.IPCIDR)
	d.Set("milestones", recNet.Milestones)
	d.Set("name", recNet.Name)
	d.Set("network_ids", flattenNetworkIDs(recNet.NetworkIDs))
	d.Set("ovs_bridge", recNet.OVSBridge)
	d.Set("pre_reservations_num", recNet.PreReservationsNum)
	d.Set("pri_vnfdev_id", recNet.PriVNFDevID)
	d.Set("shared_with", recNet.SharedWith)
	d.Set("status", recNet.Status)
	d.Set("vlan_id", recNet.VLANID)
	d.Set("check_ips", recNet.CheckIPs)
	d.Set("dns", recNet.DNS)
	d.Set("excluded", flattenExtnetExcluded(recNet.Excluded))
	d.Set("gateway", recNet.Gateway)
	d.Set("network", recNet.Network)
	d.Set("ntp", recNet.NTP)
	d.Set("prefix", recNet.Prefix)
	d.Set("default_qos", flattenExtnetDefaultQos(recNet.DefaultQOS))
	d.Set("vnfs", flattenExtnetVNFS(recNet.VNFs))
	d.Set("reservations", flattenExtnetReservations(recNet.Reservations))
	d.Set("routes", flattenStaticRouteList(staticRouteList))
	d.Set("zone_id", recNet.ZoneID)
	d.Set("enable_secgroups", recNet.EnableSecGroups)
}

func flattenExtnetExcluded(ers extnet.ListReservations) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	for _, er := range ers {
		temp := map[string]interface{}{
			"client_type": er.ClientType,
			"desc":        er.Description,
			"domain_name": er.DomainName,
			"hostname":    er.Hostname,
			"ip":          er.IP,
			"mac":         er.MAC,
			"type":        er.Type,
			"vm_id":       er.VMID,
		}
		res = append(res, temp)
	}

	return res
}

func flattenExtnetReservations(ers extnet.ListReservations) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	for _, er := range ers {
		temp := map[string]interface{}{
			"account_id":  er.AccountID,
			"client_type": er.ClientType,
			"domain_name": er.DomainName,
			"hostname":    er.Hostname,
			"desc":        er.Description,
			"ip":          er.IP,
			"mac":         er.MAC,
			"type":        er.Type,
			"vm_id":       er.VMID,
		}
		res = append(res, temp)
	}

	return res
}

func flattenExtnetVNFS(evnfs extnet.VNFs) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	temp := map[string]interface{}{
		"dhcp": evnfs.DHCP,
	}
	res = append(res, temp)
	return res
}

func flattenExtnetDefaultQos(edqos extnet.QOS) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	temp := map[string]interface{}{
		"e_rate":   edqos.ERate,
		"guid":     edqos.GUID,
		"in_burst": edqos.InBurst,
		"in_rate":  edqos.InRate,
	}
	res = append(res, temp)
	return res
}

func flattenStaticRouteList(sr *extnet.ListStaticRoutes) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(sr.Data))
	for _, staticRoute := range sr.Data {
		temp := map[string]interface{}{
			"route_id":    staticRoute.ID,
			"destination": staticRoute.Destination,
			"gateway":     staticRoute.Gateway,
			"guid":        staticRoute.GUID,
			"netmask":     staticRoute.Netmask,
			"compute_ids": staticRoute.ComputeIds,
		}
		res = append(res, temp)
	}

	return res
}

func flattenStaticRouteData(d *schema.ResourceData, route *extnet.ItemRoutes) {
	d.Set("destination", route.Destination)
	d.Set("gateway", route.Gateway)
	d.Set("guid", route.GUID)
	d.Set("netmask", route.Netmask)
	d.Set("compute_ids", route.ComputeIds)
	d.Set("route_id", route.ID)
}

func flattenExtnetReservedIp(el []extnet.RecordReservedIP) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(el))
	for _, e := range el {
		reservations := make([]map[string]interface{}, 0, len(e.Reservations))
		for _, r := range e.Reservations {
			temp := map[string]interface{}{
				"account_id":  r.AccountID,
				"client_type": r.ClientType,
				"domain_name": r.DomainName,
				"hostname":    r.Hostname,
				"ip":          r.IP,
				"mac":         r.Mac,
				"type":        r.Type,
				"vm_id":       r.VMID,
			}
			reservations = append(reservations, temp)
		}
		item := map[string]interface{}{
			"extnet_id":    e.ExtnetID,
			"reservations": reservations,
		}
		res = append(res, item)
	}
	return res
}

func flattenNetworkIDs(ex extnet.NetworkIDs) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, 1)
	temp := map[string]interface{}{
		"primary":   ex.Primary,
		"secondary": ex.Secondary,
	}
	res = append(res, temp)

	return res
}
