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

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

func flattenLBFrontendBind(d *schema.ResourceData, b *lb.ItemBinding, lbId int64, frontendName string) {
	d.Set("lb_id", lbId)
	d.Set("frontend_name", frontendName)
	d.Set("name", b.Name)
	d.Set("address", b.Address)
	d.Set("guid", b.GUID)
	d.Set("port", b.Port)
}

func flattenLBFrontend(d *schema.ResourceData, f *lb.ItemFrontend, lbId int64) {
	d.Set("lb_id", lbId)
	d.Set("backend_name", f.Backend)
	d.Set("name", f.Name)
	d.Set("guid", f.GUID)
	d.Set("bindings", flattendBindings(f.Bindings))
}

func flattenResourceLBBackendServer(d *schema.ResourceData, s *lb.ItemServer, lbId int64, backendName string) {
	d.Set("lb_id", lbId)
	d.Set("backend_name", backendName)
	d.Set("name", s.Name)
	d.Set("port", s.Port)
	d.Set("address", s.Address)
	d.Set("check", s.Check)
	d.Set("guid", s.GUID)
	d.Set("downinter", s.ServerSettings.DownInter)
	d.Set("fall", s.ServerSettings.Fall)
	d.Set("inter", s.ServerSettings.Inter)
	d.Set("maxconn", s.ServerSettings.MaxConn)
	d.Set("maxqueue", s.ServerSettings.MaxQueue)
	d.Set("rise", s.ServerSettings.Rise)
	d.Set("slowstart", s.ServerSettings.SlowStart)
	d.Set("weight", s.ServerSettings.Weight)

}

func flattenResourceLBBackend(d *schema.ResourceData, b *lb.ItemBackend, lbId int64) {
	d.Set("lb_id", lbId)
	d.Set("name", b.Name)
	d.Set("algorithm", b.Algorithm)
	d.Set("guid", b.GUID)
	d.Set("downinter", b.ServerDefaultSettings.DownInter)
	d.Set("fall", b.ServerDefaultSettings.Fall)
	d.Set("inter", b.ServerDefaultSettings.Inter)
	d.Set("maxconn", b.ServerDefaultSettings.MaxConn)
	d.Set("maxqueue", b.ServerDefaultSettings.MaxQueue)
	d.Set("rise", b.ServerDefaultSettings.Rise)
	d.Set("slowstart", b.ServerDefaultSettings.SlowStart)
	d.Set("weight", b.ServerDefaultSettings.Weight)
	d.Set("servers", flattenServers(b.Servers))
}

func flattenResourceLB(d *schema.ResourceData, lb *lb.RecordLB) {
	d.Set("ha_mode", lb.HAMode)
	d.Set("backend_haip", lb.BackendHAIP)
	d.Set("backends", flattenLBBackends(lb.Backends))
	d.Set("created_by", lb.CreatedBy)
	d.Set("created_time", lb.CreatedTime)
	d.Set("deleted_by", lb.DeletedBy)
	d.Set("deleted_time", lb.DeletedTime)
	d.Set("desc", lb.Description)
	d.Set("dp_api_user", lb.DPAPIUser)
	d.Set("extnet_id", lb.ExtNetID)
	d.Set("frontend_haip", lb.FrontendHAIP)
	d.Set("frontends", flattenFrontends(lb.Frontends))
	d.Set("gid", lb.GID)
	d.Set("guid", lb.GUID)
	d.Set("manager_id", lb.ManagerId)
	d.Set("manager_type", lb.ManagerType)
	d.Set("lb_id", lb.ID)
	d.Set("image_id", lb.ImageID)
	d.Set("milestones", lb.Milestones)
	d.Set("name", lb.Name)
	d.Set("part_k8s", lb.PartK8s)
	d.Set("primary_node", flattenNode(lb.PrimaryNode))
	d.Set("rg_id", lb.RGID)
	d.Set("rg_name", lb.RGName)
	d.Set("secondary_node", flattenNode(lb.SecondaryNode))
	d.Set("status", lb.Status)
	d.Set("tech_status", lb.TechStatus)
	d.Set("updated_by", lb.UpdatedBy)
	d.Set("updated_time", lb.UpdatedTime)
	d.Set("user_managed", lb.UserManaged)
	d.Set("vins_id", lb.VINSID)
	d.Set("zone_id", lb.ZoneID)

}

func flattenLB(d *schema.ResourceData, lb *lb.RecordLB) {
	d.Set("account_id", lb.AccountID)
	d.Set("ha_mode", lb.HAMode)
	d.Set("backend_haip", lb.BackendHAIP)
	d.Set("backends", flattenLBBackends(lb.Backends))
	d.Set("created_by", lb.CreatedBy)
	d.Set("created_time", lb.CreatedTime)
	d.Set("deleted_by", lb.DeletedBy)
	d.Set("deleted_time", lb.DeletedTime)
	d.Set("desc", lb.Description)
	d.Set("dp_api_user", lb.DPAPIUser)
	d.Set("extnet_id", lb.ExtNetID)
	d.Set("frontend_haip", lb.FrontendHAIP)
	d.Set("frontends", flattenFrontends(lb.Frontends))
	d.Set("gid", lb.GID)
	d.Set("guid", lb.GUID)
	d.Set("manager_id", lb.ManagerId)
	d.Set("manager_type", lb.ManagerType)
	d.Set("image_id", lb.ImageID)
	d.Set("milestones", lb.Milestones)
	d.Set("name", lb.Name)
	d.Set("part_k8s", lb.PartK8s)
	d.Set("primary_node", flattenNode(lb.PrimaryNode))
	d.Set("rg_id", lb.RGID)
	d.Set("rg_name", lb.RGName)
	d.Set("secondary_node", flattenNode(lb.SecondaryNode))
	d.Set("status", lb.Status)
	d.Set("tech_status", lb.TechStatus)
	d.Set("updated_by", lb.UpdatedBy)
	d.Set("updated_time", lb.UpdatedTime)
	d.Set("user_managed", lb.UserManaged)
	d.Set("vins_id", lb.VINSID)
	d.Set("zone_id", lb.ZoneID)
}

func flattenNode(node lb.RecordNode) []map[string]interface{} {
	temp := make([]map[string]interface{}, 0)
	n := 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,
	}

	temp = append(temp, n)

	return temp
}

func flattendBindings(bs []lb.ItemBinding) []map[string]interface{} {
	temp := make([]map[string]interface{}, 0, len(bs))
	for _, b := range bs {
		t := map[string]interface{}{
			"address": b.Address,
			"guid":    b.GUID,
			"name":    b.Name,
			"port":    b.Port,
		}
		temp = append(temp, t)
	}
	return temp
}

func flattenFrontends(fs []lb.ItemFrontend) []map[string]interface{} {
	temp := make([]map[string]interface{}, 0, len(fs))
	for _, f := range fs {
		t := map[string]interface{}{
			"backend":  f.Backend,
			"bindings": flattendBindings(f.Bindings),
			"guid":     f.GUID,
			"name":     f.Name,
		}
		temp = append(temp, t)
	}

	return temp
}

func flattenServers(servers []lb.ItemServer) []map[string]interface{} {
	temp := make([]map[string]interface{}, 0, len(servers))
	for _, server := range servers {
		t := map[string]interface{}{
			"address":         server.Address,
			"check":           server.Check,
			"guid":            server.GUID,
			"name":            server.Name,
			"port":            server.Port,
			"server_settings": flattenServerSettings(server.ServerSettings),
		}

		temp = append(temp, t)
	}
	return temp
}

func flattenServerSettings(defSet lb.RecordServerSettings) []map[string]interface{} {
	temp := map[string]interface{}{
		"downinter": defSet.DownInter,
		"fall":      defSet.Fall,
		"guid":      defSet.GUID,
		"inter":     defSet.Inter,
		"maxconn":   defSet.MaxConn,
		"maxqueue":  defSet.MaxQueue,
		"rise":      defSet.Rise,
		"slowstart": defSet.SlowStart,
		"weight":    defSet.Weight,
	}

	res := make([]map[string]interface{}, 0)
	res = append(res, temp)
	return res
}

func flattenLBBackends(backends []lb.ItemBackend) []map[string]interface{} {
	temp := make([]map[string]interface{}, 0, len(backends))
	for _, item := range backends {
		t := map[string]interface{}{
			"algorithm":               item.Algorithm,
			"guid":                    item.GUID,
			"name":                    item.Name,
			"server_default_settings": flattenServerSettings(item.ServerDefaultSettings),
			"servers":                 flattenServers(item.Servers),
		}

		temp = append(temp, t)
	}
	return temp
}

func flattenLBList(lbl *lb.ListLB) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(lbl.Data))
	for _, lb := range lbl.Data {
		temp := map[string]interface{}{
			"ha_mode":         lb.HAMode,
			"backend_haip":    lb.BackendHAIP,
			"backends":        flattenLBBackends(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,
			"dp_api_password": lb.DPAPIPassword,
			"extnet_id":       lb.ExtNetID,
			"frontend_haip":   lb.FrontendHAIP,
			"frontends":       flattenFrontends(lb.Frontends),
			"gid":             lb.GID,
			"guid":            lb.GUID,
			"manager_id":      lb.ManagerId,
			"manager_type":    lb.ManagerType,
			"image_id":        lb.ImageID,
			"milestones":      lb.Milestones,
			"name":            lb.Name,
			"part_k8s":        lb.PartK8s,
			"primary_node":    flattenNode(lb.PrimaryNode),
			"rg_id":           lb.RGID,
			"rg_name":         lb.RGName,
			"secondary_node":  flattenNode(lb.SecondaryNode),
			"status":          lb.Status,
			"tech_status":     lb.TechStatus,
			"updated_by":      lb.UpdatedBy,
			"updated_time":    lb.UpdatedTime,
			"user_managed":    lb.UserManaged,
			"vins_id":         lb.VINSID,
			"lb_id":           lb.ID,
			"zone_id":         lb.ZoneID,
		}
		res = append(res, temp)
	}
	return res
}
