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

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 vins

import (
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/vins"
)

func flattenMGMT(mgmt vins.RecordMGMT) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	temp := map[string]interface{}{
		"ip_addr":  mgmt.IPAddress,
		"password": mgmt.Password,
		"ssh_key":  mgmt.SSHKey,
		"user":     mgmt.User,
	}
	res = append(res, temp)
	return res
}

func flattenResources(resources vins.RecordResources) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	temp := map[string]interface{}{
		"cpu":     resources.CPU,
		"ram":     resources.RAM,
		"node_id": resources.NodeID,
		"uuid":    resources.UUID,
	}
	res = append(res, temp)
	return res
}

func flattenConfig(config vins.RecordVNFConfig) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	temp := map[string]interface{}{
		"mgmt":      flattenMGMT(config.MGMT),
		"resources": flattenResources(config.Resources),
	}
	res = append(res, temp)
	return res
}

func flattenQOS(qos vins.QOS) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	temp := map[string]interface{}{
		"e_rate":   qos.ERate,
		"guid":     qos.GUID,
		"in_brust": qos.InBurst,
		"in_rate":  qos.InRate,
	}
	res = append(res, temp)
	return res
}

func flattenInterfaces(interfaces []vins.ItemVNFInterface) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(interfaces))
	for _, vnfInterface := range interfaces {
		temp := map[string]interface{}{
			"conn_id":          vnfInterface.ConnID,
			"conn_type":        vnfInterface.ConnType,
			"def_gw":           vnfInterface.DefGW,
			"enabled":          vnfInterface.Enabled,
			"enable_secgroups": vnfInterface.EnableSecGroups,
			"flipgroup_id":     vnfInterface.FLIPGroupID,
			"guid":             vnfInterface.GUID,
			"ip_address":       vnfInterface.IPAddress,
			"listen_ssh":       vnfInterface.ListenSSH,
			"mac":              vnfInterface.MAC,
			"mtu":              vnfInterface.MTU,
			"name":             vnfInterface.Name,
			"net_id":           vnfInterface.NetID,
			"net_mask":         vnfInterface.NetMask,
			"net_type":         vnfInterface.NetType,
			"node_id":          vnfInterface.NodeID,
			"pci_slot":         vnfInterface.PCISlot,
			"bus_number":       vnfInterface.BusNumber,
			"qos":              flattenQOS(vnfInterface.QOS),
			"sdn_interface_id": vnfInterface.SDNInterfaceID,
			"security_groups":  vnfInterface.SecGroups,
			"target":           vnfInterface.Target,
			"type":             vnfInterface.Type,
			"vnfs":             vnfInterface.VNFs,
			"libvirt_settings": flattenLibvirtSettings(vnfInterface.LibvirtSettings),
		}
		res = append(res, temp)
	}

	return res
}

func flattenLibvirtSettings(libvirtSettings vins.LibvirtSettings) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	temp := map[string]interface{}{
		"guid":          libvirtSettings.GUID,
		"txmode":        libvirtSettings.TXMode,
		"ioeventfd":     libvirtSettings.IOEventFD,
		"event_idx":     libvirtSettings.EventIDx,
		"queues":        libvirtSettings.Queues,
		"rx_queue_size": libvirtSettings.RXQueueSize,
		"tx_queue_size": libvirtSettings.TXQueueSize,
	}
	res = append(res, temp)
	return res
}

func flattenVNFDev(vnfDev vins.RecordVNFDev) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	temp := map[string]interface{}{
		"_ckey":                 vnfDev.CKey,
		"account_id":            vnfDev.AccountID,
		"capabilities":          vnfDev.Capabilities,
		"config":                flattenConfig(vnfDev.Config), //in progress
		"config_saved":          vnfDev.ConfigSaved,
		"custom_pre_cfg":        vnfDev.CustomPreConfig,
		"desc":                  vnfDev.Description,
		"gid":                   vnfDev.GID,
		"guid":                  vnfDev.GUID,
		"vnf_id":                vnfDev.ID,
		"interfaces":            flattenInterfaces(vnfDev.Interfaces),
		"live_migration_job_id": vnfDev.LiveMigrationJobID,
		"lock_status":           vnfDev.LockStatus,
		"milestones":            vnfDev.Milestones,
		"vnf_name":              vnfDev.Name,
		"status":                vnfDev.Status,
		"tech_status":           vnfDev.TechStatus,
		"type":                  vnfDev.Type,
		"vnc_password":          vnfDev.VNCPassword,
		"vins":                  vnfDev.VINS,
	}

	res = append(res, temp)

	return res
}

func flattenComputes(computes vins.ListVINSComputes) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(computes))
	for _, compute := range computes {
		temp := map[string]interface{}{
			"compute_id":   compute.ID,
			"compute_name": compute.Name,
		}
		res = append(res, temp)
	}

	return res
}

func flattenReservations(reservations vins.ListReservations) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(reservations))
	for _, reservation := range reservations {
		temp := map[string]interface{}{
			"account_id": reservation.AccountID,
			"ip":         reservation.IP,
			"mac":        reservation.MAC,
			"type":       reservation.Type,
			"vm_id":      reservation.VMID,
		}
		res = append(res, temp)
	}

	return res
}

func flattenDHCPConfig(config vins.RecordDHCPConfig) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	temp := map[string]interface{}{
		"default_gw":   config.DefaultGW,
		"dns":          config.DNS,
		"ip_end":       config.IPEnd,
		"ip_start":     config.IPStart,
		"lease":        config.Lease,
		"netmask":      config.NetMask,
		"network":      config.Network,
		"reservations": flattenReservations(config.Reservations),
	}
	res = append(res, temp)

	return res
}

func flattenPrimary(primary vins.RecordPrimary) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	temp := map[string]interface{}{
		"dev_id":  primary.DevID,
		"iface01": primary.IFace01,
		"iface02": primary.IFace02,
	}
	res = append(res, temp)

	return res
}

func flattenDevices(devices vins.RecordDevices) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	temp := map[string]interface{}{
		"primary": flattenPrimary(devices.Primary),
	}
	res = append(res, temp)

	return res
}

func flattenDHCP(dhcp vins.RecordDHCP) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	temp := map[string]interface{}{
		"_ckey":        dhcp.CKey,
		"account_id":   dhcp.AccountID,
		"config":       flattenDHCPConfig(dhcp.Config),
		"created_time": dhcp.CreatedTime,
		"devices":      flattenDevices(dhcp.Devices),
		"gid":          dhcp.GID,
		"guid":         dhcp.GUID,
		"dhcp_id":      dhcp.ID,
		"lock_status":  dhcp.LockStatus,
		"milestones":   dhcp.Milestones,
		"owner_id":     dhcp.OwnerID,
		"owner_type":   dhcp.OwnerType,
		"pure_virtual": dhcp.PureVirtual,
		"routes":       flattenStaticRoute(dhcp.Routes),
		"status":       dhcp.Status,
		"tech_status":  dhcp.TechStatus,
		"type":         dhcp.Type,
		"zone_id":      dhcp.ZoneID,
	}
	res = append(res, temp)

	return res
}

func flattenGWConfig(config vins.RecordGWConfig) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	temp := map[string]interface{}{
		"default_gw":  config.DefaultGW,
		"ext_net_id":  config.ExtNetID,
		"ext_net_ip":  config.ExtNetIP,
		"ext_netmask": config.ExtNetMask,
		"qos":         flattenQOS(config.QOS),
	}
	res = append(res, temp)

	return res
}

func flattenGW(gw vins.RecordGW) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	temp := map[string]interface{}{
		"_ckey":        gw.CKey,
		"account_id":   gw.AccountID,
		"config":       flattenGWConfig(gw.Config),
		"created_time": gw.CreatedTime,
		"devices":      flattenDevices(gw.Devices),
		"gid":          gw.GID,
		"guid":         gw.GUID,
		"gw_id":        gw.ID,
		"lock_status":  gw.LockStatus,
		"milestones":   gw.Milestones,
		"owner_id":     gw.OwnerID,
		"owner_type":   gw.OwnerType,
		"pure_virtual": gw.PureVirtual,
		"routes":       flattenStaticRoute(gw.Routes),
		"status":       gw.Status,
		"tech_status":  gw.TechStatus,
		"type":         gw.Type,
		"zone_id":      gw.ZoneID,
	}
	res = append(res, temp)

	return res
}

func flattenRules(rules vins.ListNATRulesConfig) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(rules))
	for _, rule := range rules {
		tmp := map[string]interface{}{
			"rule_id":           rule.ID,
			"local_ip":          rule.LocalIP,
			"local_port":        rule.LocalPort,
			"protocol":          rule.Protocol,
			"public_port_end":   rule.PublicPortEnd,
			"public_port_start": rule.PublicPortStart,
			"vm_id":             rule.VMID,
			"vm_name":           rule.VMName,
		}
		res = append(res, tmp)
	}
	return res
}

func flattenNATConfig(config vins.NATConfig) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	temp := map[string]interface{}{
		"net_mask": config.NetMask,
		"network":  config.Network,
		"rules":    flattenRules(config.Rules),
	}
	res = append(res, temp)

	return res

}

func flattenNAT(nat vins.RecordNAT) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	temp := map[string]interface{}{
		"_ckey":        nat.CKey,
		"account_id":   nat.AccountID,
		"created_time": nat.CreatedTime,
		"config":       flattenNATConfig(nat.Config),
		"devices":      flattenDevices(nat.Devices),
		"gid":          nat.GID,
		"guid":         nat.GUID,
		"nat_id":       nat.ID,
		"lock_status":  nat.LockStatus,
		"milestones":   nat.Milestones,
		"owner_id":     nat.OwnerID,
		"owner_type":   nat.OwnerType,
		"pure_virtual": nat.PureVirtual,
		"routes":       flattenStaticRoute(nat.Routes),
		"status":       nat.Status,
		"tech_status":  nat.TechStatus,
		"type":         nat.Type,
		"zone_id":      nat.ZoneID,
	}
	res = append(res, temp)

	return res
}

func flattenVNFS(vnfs vins.RecordVNFs) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	temp := map[string]interface{}{
		"dhcp": flattenDHCP(vnfs.DHCP),
		"gw":   flattenGW(vnfs.GW),
		"nat":  flattenNAT(vnfs.NAT),
	}
	res = append(res, temp)

	return res
}

func flattenRuleBlock(rules vins.ListNATRulesConfig) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(rules))
	for _, rule := range rules {
		tmp := map[string]interface{}{
			"int_ip":         rule.LocalIP,
			"int_port":       rule.LocalPort,
			"ext_port_start": rule.PublicPortStart,
			"ext_port_end":   rule.PublicPortEnd,
			"proto":          rule.Protocol,
			"rule_id":        rule.ID,
		}
		res = append(res, tmp)
	}
	return res
}

func flattenVins(d *schema.ResourceData, vins *vins.RecordVINS) {
	d.Set("vins_id", vins.ID)
	d.Set("vnf_dev", flattenVNFDev(vins.VNFDev))
	d.Set("account_id", vins.AccountID)
	d.Set("account_name", vins.AccountName)
	d.Set("computes", flattenComputes(vins.Computes))
	d.Set("created_by", vins.CreatedBy)
	d.Set("created_time", vins.CreatedTime)
	d.Set("default_gw", vins.DefaultGW)
	d.Set("default_qos", flattenQOS(vins.DefaultQOS))
	d.Set("deleted_by", vins.DeletedBy)
	d.Set("deleted_time", vins.DeletedTime)
	d.Set("desc", vins.Description)
	d.Set("enable_secgroups", vins.EnableSecGroups)
	d.Set("gid", vins.GID)
	d.Set("guid", vins.GUID)
	d.Set("lock_status", vins.LockStatus)
	d.Set("manager_id", vins.ManagerID)
	d.Set("manager_type", vins.ManagerType)
	d.Set("milestones", vins.Milestones)
	d.Set("name", vins.Name)
	d.Set("net_mask", vins.NetMask)
	d.Set("network", vins.Network)
	d.Set("pre_reservations_num", vins.PreReservaionsNum)
	d.Set("redundant", vins.Redundant)
	d.Set("rg_id", vins.RGID)
	d.Set("rg_name", vins.RGName)
	d.Set("sec_vnf_dev_id", vins.SecVNFDevID)
	d.Set("status", vins.Status)
	d.Set("updated_by", vins.UpdatedBy)
	d.Set("updated_time", vins.UpdatedTime)
	d.Set("user_managed", vins.UserManaged)
	d.Set("vnfs", flattenVNFS(vins.VNFs))
	d.Set("vxlan_id", vins.VXLANID)
	d.Set("nat_rule", flattenRuleBlock(vins.VNFs.NAT.Config.Rules))
	d.Set("zone_id", vins.ZoneID)
}

func flattenVinsData(d *schema.ResourceData, vins *vins.RecordVINS) {
	d.Set("vins_id", vins.ID)
	d.Set("vnf_dev", flattenVNFDev(vins.VNFDev))
	d.Set("account_id", vins.AccountID)
	d.Set("account_name", vins.AccountName)
	d.Set("computes", flattenComputes(vins.Computes))
	d.Set("created_by", vins.CreatedBy)
	d.Set("created_time", vins.CreatedTime)
	d.Set("default_gw", vins.DefaultGW)
	d.Set("default_qos", flattenQOS(vins.DefaultQOS))
	d.Set("deleted_by", vins.DeletedBy)
	d.Set("deleted_time", vins.DeletedTime)
	d.Set("desc", vins.Description)
	d.Set("gid", vins.GID)
	d.Set("guid", vins.GUID)
	d.Set("lock_status", vins.LockStatus)
	d.Set("manager_id", vins.ManagerID)
	d.Set("manager_type", vins.ManagerType)
	d.Set("milestones", vins.Milestones)
	d.Set("name", vins.Name)
	d.Set("net_mask", vins.NetMask)
	d.Set("network", vins.Network)
	d.Set("pre_reservations_num", vins.PreReservaionsNum)
	d.Set("redundant", vins.Redundant)
	d.Set("rg_id", vins.RGID)
	d.Set("rg_name", vins.RGName)
	d.Set("sec_vnf_dev_id", vins.SecVNFDevID)
	d.Set("status", vins.Status)
	d.Set("updated_by", vins.UpdatedBy)
	d.Set("updated_time", vins.UpdatedTime)
	d.Set("user_managed", vins.UserManaged)
	d.Set("vnfs", flattenVNFS(vins.VNFs))
	d.Set("vxlan_id", vins.VXLANID)
	d.Set("zone_id", vins.ZoneID)
}

func flattenVinsAudits(audits vins.ListAudits) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(audits))
	for _, audit := range audits {
		temp := map[string]interface{}{
			"call":          audit.Call,
			"response_time": audit.ResponseTime,
			"statuscode":    audit.StatusCode,
			"timestamp":     audit.Timestamp,
			"user":          audit.User,
		}
		res = append(res, temp)
	}

	return res
}

func flattenVinsExtNetList(extNetList *vins.ListExtNets) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(extNetList.Data))
	for _, extNet := range extNetList.Data {
		temp := map[string]interface{}{
			"default_gw":  extNet.DefaultGW,
			"ext_net_id":  extNet.ExtNetID,
			"ip":          extNet.IP,
			"prefix_len":  extNet.PrefixLen,
			"status":      extNet.Status,
			"tech_status": extNet.TechStatus,
		}
		res = append(res, temp)
	}

	return res
}

func flattenVinsIpList(ips *vins.ListIPs) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(ips.Data))
	for _, ip := range ips.Data {
		temp := map[string]interface{}{
			"client_type": ip.ClientType,
			"domainname":  ip.DomainName,
			"hostname":    ip.Hostname,
			"ip":          ip.IP,
			"mac":         ip.MAC,
			"type":        ip.Type,
			"vm_id":       ip.VMID,
		}
		res = append(res, temp)
	}

	return res
}

func flattenVinsList(vl *vins.ListVINS) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(vl.Data))
	for _, v := range vl.Data {
		temp := map[string]interface{}{
			"account_id":   v.AccountID,
			"account_name": v.AccountName,
			"created_by":   v.CreatedBy,
			"created_time": v.CreatedTime,
			"deleted_by":   v.DeletedBy,
			"deleted_time": v.DeletedTime,
			"external_ip":  v.ExternalIP,
			"extnet_id":    v.ExtnetId,
			"free_ips":     v.FreeIPs,
			"vins_id":      v.ID,
			"vins_name":    v.Name,
			"network":      v.Network,
			"rg_id":        v.RGID,
			"rg_name":      v.RGName,
			"status":       v.Status,
			"updated_by":   v.UpdatedBy,
			"updated_time": v.UpdatedTime,
			"vxlan_id":     v.VXLANID,
		}
		res = append(res, temp)
	}
	return res
}

func flattenVinsListDeleted(vl *vins.ListVINS) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(vl.Data))
	for _, v := range vl.Data {
		temp := map[string]interface{}{
			"account_id":   v.AccountID,
			"account_name": v.AccountName,
			"created_by":   v.CreatedBy,
			"created_time": v.CreatedTime,
			"deleted_by":   v.DeletedBy,
			"deleted_time": v.DeletedTime,
			"external_ip":  v.ExternalIP,
			"vins_id":      v.ID,
			"vins_name":    v.Name,
			"network":      v.Network,
			"rg_id":        v.RGID,
			"rg_name":      v.RGName,
			"status":       v.Status,
			"updated_by":   v.UpdatedBy,
			"updated_time": v.UpdatedTime,
			"vxlan_id":     v.VXLANID,
		}
		res = append(res, temp)
	}
	return res
}

// /4.4.0
func flattenStaticRouteList(sr *vins.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 *vins.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 flattenStaticRoute(sr vins.ListRoutes) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(sr))
	for _, staticRoute := range sr {
		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 flattenVinsNatRuleList(natRules *vins.ListNATRules) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(natRules.Data))
	for _, natRule := range natRules.Data {
		temp := map[string]interface{}{
			"id":                natRule.ID,
			"local_ip":          natRule.LocalIP,
			"local_port":        natRule.LocalPort,
			"protocol":          natRule.Protocol,
			"public_port_end":   natRule.PublicPortEnd,
			"public_port_start": natRule.PublicPortStart,
			"vm_id":             natRule.VMID,
			"vm_name":           natRule.VMName,
		}
		res = append(res, temp)
	}

	return res
}
