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

import (
	"strings"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/compute"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8ci"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/k8s"
)

func flattenK8CIItems(list *k8ci.ListK8CI) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(list.Data))
	for _, item := range list.Data {
		temp := map[string]interface{}{
			"k8ci_id":         item.ID,
			"name":            item.Name,
			"lb_image_id":     item.LBImageID,
			"network_plugins": item.NetworkPlugins,
			"status":          item.Status,
			"desc":            item.Description,
			"created_time":    item.CreatedTime,
			"version":         item.Version,
		}

		res = append(res, temp)
	}

	return res
}

func flattenK8CIList(d *schema.ResourceData, list *k8ci.ListK8CI) {
	d.Set("items", flattenK8CIItems(list))
}

func flattenK8sDataComputes(d *schema.ResourceData, cluster *k8s.RecordK8S) {
	d.Set("k8s_id", cluster.ID)
	d.Set("masters", flattenMasterComputes(cluster))
	d.Set("workers", flattenWorkerComputes(cluster))
}

func flattenMasterComputes(cluster *k8s.RecordK8S) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(cluster.K8SGroups.Masters.DetailedInfo))
	for _, comp := range cluster.K8SGroups.Masters.DetailedInfo {
		temp := map[string]interface{}{
			"id":          comp.ID,
			"name":        comp.Name,
			"status":      comp.Status,
			"tech_status": comp.TechStatus,
			"group_name":  cluster.K8SGroups.Masters.Name,
		}
		res = append(res, temp)
	}

	return res
}

func flattenWorkerComputes(cluster *k8s.RecordK8S) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(cluster.K8SGroups.Workers))
	for _, wg := range cluster.K8SGroups.Workers {
		for _, comp := range wg.DetailedInfo {
			temp := map[string]interface{}{
				"id":          comp.ID,
				"name":        comp.Name,
				"status":      comp.Status,
				"tech_status": comp.TechStatus,
				"group_name":  wg.Name,
			}
			res = append(res, temp)
		}
	}

	return res
}

func flattenAclList(aclList k8s.ListACL) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(aclList))
	for _, acl := range aclList {
		temp := map[string]interface{}{
			"explicit":      acl.Explicit,
			"guid":          acl.GUID,
			"right":         acl.Right,
			"status":        acl.Status,
			"type":          acl.Type,
			"user_group_id": acl.UserGroupID,
		}
		res = append(res, temp)
	}
	return res
}

func flattenAcl(acl k8s.RecordACL) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	temp := map[string]interface{}{
		"account_acl": flattenAclList(acl.AccountACL),
		"k8s_acl":     flattenAclList(acl.K8SACL),
		"rg_acl":      flattenAclList(acl.RGACL),
	}

	res = append(res, temp)
	return res
}

func flattenInterfaces(interfaces compute.ListInterfaces) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(interfaces))
	for _, interfaceCompute := range interfaces {
		temp := map[string]interface{}{
			"def_gw":     interfaceCompute.DefGW,
			"ip_address": interfaceCompute.IPAddress,
		}
		res = append(res, temp)
	}

	return res
}

func flattenDetailedInfo(detailedInfoList k8s.ListDetailedInfo, computes []compute.RecordCompute) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(detailedInfoList))
	if computes != nil {
		for i, detailedInfo := range detailedInfoList {
			temp := map[string]interface{}{
				"compute_id":           detailedInfo.ID,
				"name":                 detailedInfo.Name,
				"status":               detailedInfo.Status,
				"tech_status":          detailedInfo.TechStatus,
				"interfaces":           flattenInterfaces(computes[i].Interfaces),
				"natable_vins_ip":      computes[i].NatableVINSIP,
				"natable_vins_network": computes[i].NatableVINSNetwork,
			}
			res = append(res, temp)
		}
	} else {
		for _, detailedInfo := range detailedInfoList {
			temp := map[string]interface{}{
				"compute_id":  detailedInfo.ID,
				"name":        detailedInfo.Name,
				"status":      detailedInfo.Status,
				"tech_status": detailedInfo.TechStatus,
			}
			res = append(res, temp)
		}
	}

	return res
}

func flattenMasterGroup(mastersGroup k8s.MasterGroup, masters []compute.RecordCompute) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	temp := map[string]interface{}{
		"cpu":           mastersGroup.CPU,
		"detailed_info": flattenDetailedInfo(mastersGroup.DetailedInfo, masters),
		"disk":          mastersGroup.Disk,
		"master_id":     mastersGroup.ID,
		"name":          mastersGroup.Name,
		"num":           mastersGroup.Num,
		"ram":           mastersGroup.RAM,
	}

	res = append(res, temp)
	return res
}

func flattenK8sGroup(k8SGroupList k8s.ListK8SGroups, workers []compute.RecordCompute) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(k8SGroupList))
	for _, k8sGroup := range k8SGroupList {
		labels := make([]string, 0)
		for _, label := range k8sGroup.Labels {
			if strings.HasPrefix(label, "workersGroupName") {
				continue
			}

			labels = append(labels, label)
		}
		temp := map[string]interface{}{
			"annotations":   k8sGroup.Annotations,
			"cpu":           k8sGroup.CPU,
			"detailed_info": flattenDetailedInfo(k8sGroup.DetailedInfo, workers),
			"disk":          k8sGroup.Disk,
			"guid":          k8sGroup.GUID,
			"id":            k8sGroup.ID,
			"labels":        labels,
			"name":          k8sGroup.Name,
			"num":           k8sGroup.Num,
			"ram":           k8sGroup.RAM,
			"taints":        k8sGroup.Taints,
		}

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

// func flattenK8sGroups(k8sGroups k8s.RecordK8SGroups, masters []compute.RecordCompute, workers []compute.RecordCompute) []map[string]interface{} {
// 	res := make([]map[string]interface{}, 0)
// 	temp := map[string]interface{}{
// 		"masters": flattenMasterGroup(k8sGroups.Masters, masters),
// 		"workers": flattenK8sGroup(k8sGroups.Workers, workers),
// 	}
// 	res = append(res, temp)
// 	return res
// }

func flattenK8sData(d *schema.ResourceData, cluster k8s.RecordK8S, masters []compute.RecordCompute, workers []compute.RecordCompute) {
	d.Set("acl", flattenAcl(cluster.ACL))
	d.Set("account_id", cluster.AccountID)
	d.Set("account_name", cluster.AccountName)
	d.Set("bservice_id", cluster.BServiceID)
	d.Set("k8sci_id", cluster.CIID)
	d.Set("created_by", cluster.CreatedBy)
	d.Set("created_time", cluster.CreatedTime)
	d.Set("desc", cluster.Description)
	d.Set("deleted_by", cluster.DeletedBy)
	d.Set("deleted_time", cluster.DeletedTime)
	d.Set("k8s_ci_name", cluster.K8CIName)
	d.Set("masters", flattenMasterGroup(cluster.K8SGroups.Masters, masters))
	d.Set("workers", flattenK8sGroup(cluster.K8SGroups.Workers, workers))
	d.Set("lb_id", cluster.LBID)
	d.Set("name", cluster.Name)
	d.Set("network_plugin", cluster.NetworkPlugin)
	d.Set("rg_id", cluster.RGID)
	d.Set("rg_name", cluster.RGName)
	d.Set("status", cluster.Status)
	d.Set("tech_status", cluster.TechStatus)
	d.Set("updated_by", cluster.UpdatedBy)
	d.Set("updated_time", cluster.UpdatedTime)
	d.Set("highly_available_lb", cluster.HighlyAvailableLB)
	d.Set("address_vip", flattenAddressVIP(cluster.AddressVIP))
	d.Set("extnet_only", cluster.ExtnetOnly)
	d.Set("with_lb", cluster.WithLB)
	d.Set("zone_id", cluster.ZoneID)
}

func flattenAddressVIP(addressVIP k8s.K8SAddressVIP) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	temp := map[string]interface{}{
		"backend_ip":  addressVIP.BackendIP,
		"frontend_ip": addressVIP.FrontendIP,
	}
	res = append(res, temp)
	return res
}

func flattenServiceAccount(serviceAccount k8s.RecordServiceAccount) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	temp := map[string]interface{}{
		"guid":     serviceAccount.GUID,
		"password": serviceAccount.Password,
		"username": serviceAccount.Username,
	}
	res = append(res, temp)
	return res
}

func flattenWorkersGroup(workersGroups k8s.ListK8SGroups) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(workersGroups))
	for _, worker := range workersGroups {
		temp := map[string]interface{}{
			"annotations":      worker.Annotations,
			"cpu":              worker.CPU,
			"detailed_info":    flattenDetailedInfo(worker.DetailedInfo, nil),
			"disk":             worker.Disk,
			"guid":             worker.GUID,
			"detailed_info_id": worker.ID,
			"labels":           worker.Labels,
			"name":             worker.Name,
			"num":              worker.Num,
			"ram":              worker.RAM,
			"taints":           worker.Taints,
		}
		res = append(res, temp)
	}
	return res
}

func flattenK8sItems(k8sItems *k8s.ListK8SClusters) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(k8sItems.Data))
	for _, item := range k8sItems.Data {
		temp := map[string]interface{}{
			"account_id":      item.AccountID,
			"account_name":    item.AccountName,
			"acl":             item.ACL,
			"bservice_id":     item.BServiceID,
			"ci_id":           item.CIID,
			"created_by":      item.CreatedBy,
			"created_time":    item.CreatedTime,
			"deleted_by":      item.DeletedBy,
			"deleted_time":    item.DeletedTime,
			"desc":            item.Description,
			"extnet_id":       item.ExtNetID,
			"gid":             item.GID,
			"guid":            item.GUID,
			"k8s_id":          item.ID,
			"lb_id":           item.LBID,
			"milestones":      item.Milestones,
			"k8s_name":        item.Name,
			"network_plugin":  item.NetworkPlugin,
			"rg_id":           item.RGID,
			"rg_name":         item.RGName,
			"service_account": flattenServiceAccount(item.ServiceAccount),
			"status":          item.Status,
			"tech_status":     item.TechStatus,
			"updated_by":      item.UpdatedBy,
			"updated_time":    item.UpdatedTime,
			"vins_id":         item.VINSID,
			"zone_id":         item.ZoneID,
			"workers_groups":  flattenWorkersGroup(item.WorkersGroup),
		}

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

func flattenK8sList(d *schema.ResourceData, k8sItems *k8s.ListK8SClusters) {
	d.Set("items", flattenK8sItems(k8sItems))
	d.Set("entry_count", k8sItems.EntryCount)
}

func flattenResourceK8sCP(d *schema.ResourceData, k8s k8s.RecordK8S, masters []compute.RecordCompute) {
	d.Set("acl", flattenAcl(k8s.ACL))
	d.Set("account_id", k8s.AccountID)
	d.Set("account_name", k8s.AccountName)
	d.Set("k8sci_id", k8s.CIID)
	d.Set("bservice_id", k8s.BServiceID)
	d.Set("created_by", k8s.CreatedBy)
	d.Set("created_time", k8s.CreatedTime)
	d.Set("desc", k8s.Description)
	d.Set("deleted_by", k8s.DeletedBy)
	d.Set("deleted_time", k8s.DeletedTime)
	d.Set("k8s_ci_name", k8s.K8CIName)
	d.Set("with_lb", k8s.LBID != 0)
	d.Set("lb_id", k8s.LBID)
	d.Set("k8s_id", k8s.ID)
	d.Set("name", k8s.Name)
	d.Set("rg_id", k8s.RGID)
	d.Set("rg_name", k8s.RGName)
	d.Set("status", k8s.Status)
	d.Set("tech_status", k8s.TechStatus)
	d.Set("updated_by", k8s.UpdatedBy)
	d.Set("updated_time", k8s.UpdatedTime)
	d.Set("network_plugin", k8s.NetworkPlugin)
	d.Set("zone_id", k8s.ZoneID)

	flattenCPParams(d, k8s.K8SGroups.Masters, masters)
}

func flattenCPParams(d *schema.ResourceData, mastersGroup k8s.MasterGroup, masters []compute.RecordCompute) {
	d.Set("cpu", mastersGroup.CPU)
	d.Set("detailed_info", flattenDetailedInfo(mastersGroup.DetailedInfo, masters))
	d.Set("disk", mastersGroup.Disk)
	d.Set("master_id", mastersGroup.ID)
	d.Set("master_name", mastersGroup.Name)
	d.Set("num", mastersGroup.Num)
	d.Set("ram", mastersGroup.RAM)
	d.Set("master_id", mastersGroup.ID)
}

func flattenResourceK8s(d *schema.ResourceData, k8s k8s.RecordK8S, masters []compute.RecordCompute, workers []compute.RecordCompute) {
	wg_name := k8s.K8SGroups.Workers[0].Name

	d.Set("acl", flattenAcl(k8s.ACL))
	d.Set("account_id", k8s.AccountID)
	d.Set("account_name", k8s.AccountName)
	d.Set("k8sci_id", k8s.CIID)
	d.Set("wg_name", wg_name)
	d.Set("bservice_id", k8s.BServiceID)
	d.Set("created_by", k8s.CreatedBy)
	d.Set("created_time", k8s.CreatedTime)
	d.Set("desc", k8s.Description)
	d.Set("deleted_by", k8s.DeletedBy)
	d.Set("deleted_time", k8s.DeletedTime)
	d.Set("k8s_ci_name", k8s.K8CIName)
	d.Set("masters", flattenMasterGroup(k8s.K8SGroups.Masters, masters))
	d.Set("workers", flattenK8sGroup(k8s.K8SGroups.Workers, workers))
	d.Set("with_lb", k8s.LBID != 0)
	d.Set("lb_id", k8s.LBID)
	d.Set("name", k8s.Name)
	d.Set("rg_id", k8s.RGID)
	d.Set("rg_name", k8s.RGName)
	d.Set("status", k8s.Status)
	d.Set("tech_status", k8s.TechStatus)
	d.Set("updated_by", k8s.UpdatedBy)
	d.Set("updated_time", k8s.UpdatedTime)
	d.Set("default_wg_id", k8s.K8SGroups.Workers[0].ID)
	d.Set("network_plugin", k8s.NetworkPlugin)
	d.Set("zone_id", k8s.ZoneID)
}

func flattenWg(d *schema.ResourceData, wg k8s.ItemK8SGroup, computes []compute.RecordCompute) {
	labels := make([]string, 0, len(wg.Labels))
	for _, label := range wg.Labels {
		if strings.HasPrefix(label, "workersGroupName") {
			continue
		}

		labels = append(labels, label)
	}

	d.Set("annotations", wg.Annotations)
	d.Set("cpu", wg.CPU)
	d.Set("detailed_info", flattenDetailedInfo(wg.DetailedInfo, computes))
	d.Set("disk", wg.Disk)
	d.Set("guid", wg.GUID)
	d.Set("labels", labels)
	d.Set("name", wg.Name)
	d.Set("num", wg.Num)
	d.Set("ram", wg.RAM)
	d.Set("taints", wg.Taints)
}

func flattenWgList(wgList k8s.ListK8SGroups, computesMap map[uint64][]compute.RecordCompute) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(wgList))
	for _, wg := range wgList {
		computes := computesMap[wg.ID]
		temp := map[string]interface{}{
			"annotations":   wg.Annotations,
			"cpu":           wg.CPU,
			"wg_id":         wg.ID,
			"detailed_info": flattenDetailedInfo(wg.DetailedInfo, computes),
			"disk":          wg.Disk,
			"guid":          wg.GUID,
			"labels":        wg.Labels,
			"name":          wg.Name,
			"num":           wg.Num,
			"ram":           wg.RAM,
			"taints":        wg.Taints,
		}

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

func flattenItemsWg(d *schema.ResourceData, wgList k8s.ListK8SGroups, computes map[uint64][]compute.RecordCompute) {
	d.Set("items", flattenWgList(wgList, computes))
}
