// Copyright © 2023 Cisco Systems, Inc. and its affiliates.
// All rights reserved.
//
// Licensed under the Mozilla Public 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
//
//     https://mozilla.org/MPL/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.
//
// SPDX-License-Identifier: MPL-2.0

// Code generated by "gen/generator.go"; DO NOT EDIT.

package provider

// Section below is generated&owned by "gen/generator.go". //template:begin imports
import (
	"context"
	"fmt"
	"reflect"
	"regexp"
	"strconv"
	"strings"

	"github.com/CiscoDevNet/terraform-provider-iosxe/internal/provider/helpers"
	"github.com/hashicorp/terraform-plugin-framework/types"
	"github.com/tidwall/gjson"
	"github.com/tidwall/sjson"
)

// End of section. //template:end imports

// Section below is generated&owned by "gen/generator.go". //template:begin types
type SpanningTree struct {
	Device                   types.String               `tfsdk:"device"`
	Id                       types.String               `tfsdk:"id"`
	Mode                     types.String               `tfsdk:"mode"`
	LoopguardDefault         types.Bool                 `tfsdk:"loopguard_default"`
	PortfastDefault          types.Bool                 `tfsdk:"portfast_default"`
	PortfastBpduguardDefault types.Bool                 `tfsdk:"portfast_bpduguard_default"`
	ExtendSystemId           types.Bool                 `tfsdk:"extend_system_id"`
	MstInstances             []SpanningTreeMstInstances `tfsdk:"mst_instances"`
}

type SpanningTreeData struct {
	Device                   types.String               `tfsdk:"device"`
	Id                       types.String               `tfsdk:"id"`
	Mode                     types.String               `tfsdk:"mode"`
	LoopguardDefault         types.Bool                 `tfsdk:"loopguard_default"`
	PortfastDefault          types.Bool                 `tfsdk:"portfast_default"`
	PortfastBpduguardDefault types.Bool                 `tfsdk:"portfast_bpduguard_default"`
	ExtendSystemId           types.Bool                 `tfsdk:"extend_system_id"`
	MstInstances             []SpanningTreeMstInstances `tfsdk:"mst_instances"`
}
type SpanningTreeMstInstances struct {
	Id      types.Int64 `tfsdk:"id"`
	VlanIds types.List  `tfsdk:"vlan_ids"`
}

// End of section. //template:end types

// Section below is generated&owned by "gen/generator.go". //template:begin getPath

func (data SpanningTree) getPath() string {
	return "Cisco-IOS-XE-native:native/spanning-tree"
}

func (data SpanningTreeData) getPath() string {
	return "Cisco-IOS-XE-native:native/spanning-tree"
}

// if last path element has a key -> remove it
func (data SpanningTree) getPathShort() string {
	path := data.getPath()
	re := regexp.MustCompile(`(.*)=[^\/]*$`)
	matches := re.FindStringSubmatch(path)
	if len(matches) <= 1 {
		return path
	}
	return matches[1]
}

// End of section. //template:end getPath

// Section below is generated&owned by "gen/generator.go". //template:begin toBody

func (data SpanningTree) toBody(ctx context.Context) string {
	body := `{"` + helpers.LastElement(data.getPath()) + `":{}}`
	if !data.Mode.IsNull() && !data.Mode.IsUnknown() {
		body, _ = sjson.Set(body, helpers.LastElement(data.getPath())+"."+"Cisco-IOS-XE-spanning-tree:mode", data.Mode.ValueString())
	}
	if !data.LoopguardDefault.IsNull() && !data.LoopguardDefault.IsUnknown() {
		if data.LoopguardDefault.ValueBool() {
			body, _ = sjson.Set(body, helpers.LastElement(data.getPath())+"."+"Cisco-IOS-XE-spanning-tree:loopguard.default", map[string]string{})
		}
	}
	if !data.PortfastDefault.IsNull() && !data.PortfastDefault.IsUnknown() {
		if data.PortfastDefault.ValueBool() {
			body, _ = sjson.Set(body, helpers.LastElement(data.getPath())+"."+"Cisco-IOS-XE-spanning-tree:portfast.default", map[string]string{})
		}
	}
	if !data.PortfastBpduguardDefault.IsNull() && !data.PortfastBpduguardDefault.IsUnknown() {
		if data.PortfastBpduguardDefault.ValueBool() {
			body, _ = sjson.Set(body, helpers.LastElement(data.getPath())+"."+"Cisco-IOS-XE-spanning-tree:portfast.bpduguard.default", map[string]string{})
		}
	}
	if !data.ExtendSystemId.IsNull() && !data.ExtendSystemId.IsUnknown() {
		if data.ExtendSystemId.ValueBool() {
			body, _ = sjson.Set(body, helpers.LastElement(data.getPath())+"."+"Cisco-IOS-XE-spanning-tree:extend.system-id", map[string]string{})
		}
	}
	if len(data.MstInstances) > 0 {
		body, _ = sjson.Set(body, helpers.LastElement(data.getPath())+"."+"Cisco-IOS-XE-spanning-tree:mst.configuration.instance", []interface{}{})
		for index, item := range data.MstInstances {
			if !item.Id.IsNull() && !item.Id.IsUnknown() {
				body, _ = sjson.Set(body, helpers.LastElement(data.getPath())+"."+"Cisco-IOS-XE-spanning-tree:mst.configuration.instance"+"."+strconv.Itoa(index)+"."+"id", strconv.FormatInt(item.Id.ValueInt64(), 10))
			}
			if !item.VlanIds.IsNull() && !item.VlanIds.IsUnknown() {
				var values []int
				item.VlanIds.ElementsAs(ctx, &values, false)
				body, _ = sjson.Set(body, helpers.LastElement(data.getPath())+"."+"Cisco-IOS-XE-spanning-tree:mst.configuration.instance"+"."+strconv.Itoa(index)+"."+"vlan-ids", values)
			}
		}
	}
	return body
}

// End of section. //template:end toBody

// Section below is generated&owned by "gen/generator.go". //template:begin updateFromBody

func (data *SpanningTree) updateFromBody(ctx context.Context, res gjson.Result) {
	prefix := helpers.LastElement(data.getPath()) + "."
	if res.Get(helpers.LastElement(data.getPath())).IsArray() {
		prefix += "0."
	}
	if value := res.Get(prefix + "Cisco-IOS-XE-spanning-tree:mode"); value.Exists() && !data.Mode.IsNull() {
		data.Mode = types.StringValue(value.String())
	} else {
		data.Mode = types.StringNull()
	}
	if value := res.Get(prefix + "Cisco-IOS-XE-spanning-tree:loopguard.default"); !data.LoopguardDefault.IsNull() {
		if value.Exists() {
			data.LoopguardDefault = types.BoolValue(true)
		} else {
			data.LoopguardDefault = types.BoolValue(false)
		}
	} else {
		data.LoopguardDefault = types.BoolNull()
	}
	if value := res.Get(prefix + "Cisco-IOS-XE-spanning-tree:portfast.default"); !data.PortfastDefault.IsNull() {
		if value.Exists() {
			data.PortfastDefault = types.BoolValue(true)
		} else {
			data.PortfastDefault = types.BoolValue(false)
		}
	} else {
		data.PortfastDefault = types.BoolNull()
	}
	if value := res.Get(prefix + "Cisco-IOS-XE-spanning-tree:portfast.bpduguard.default"); !data.PortfastBpduguardDefault.IsNull() {
		if value.Exists() {
			data.PortfastBpduguardDefault = types.BoolValue(true)
		} else {
			data.PortfastBpduguardDefault = types.BoolValue(false)
		}
	} else {
		data.PortfastBpduguardDefault = types.BoolNull()
	}
	if value := res.Get(prefix + "Cisco-IOS-XE-spanning-tree:extend.system-id"); !data.ExtendSystemId.IsNull() {
		if value.Exists() {
			data.ExtendSystemId = types.BoolValue(true)
		} else {
			data.ExtendSystemId = types.BoolValue(false)
		}
	} else {
		data.ExtendSystemId = types.BoolNull()
	}
	for i := range data.MstInstances {
		keys := [...]string{"id"}
		keyValues := [...]string{strconv.FormatInt(data.MstInstances[i].Id.ValueInt64(), 10)}

		var r gjson.Result
		res.Get(prefix + "Cisco-IOS-XE-spanning-tree:mst.configuration.instance").ForEach(
			func(_, v gjson.Result) bool {
				found := false
				for ik := range keys {
					if v.Get(keys[ik]).String() == keyValues[ik] {
						found = true
						continue
					}
					found = false
					break
				}
				if found {
					r = v
					return false
				}
				return true
			},
		)
		if value := r.Get("id"); value.Exists() && !data.MstInstances[i].Id.IsNull() {
			data.MstInstances[i].Id = types.Int64Value(value.Int())
		} else {
			data.MstInstances[i].Id = types.Int64Null()
		}
		if value := r.Get("vlan-ids"); value.Exists() && !data.MstInstances[i].VlanIds.IsNull() {
			data.MstInstances[i].VlanIds = helpers.GetInt64List(value.Array())
		} else {
			data.MstInstances[i].VlanIds = types.ListNull(types.Int64Type)
		}
	}
}

// End of section. //template:end updateFromBody

// Section below is generated&owned by "gen/generator.go". //template:begin fromBody

func (data *SpanningTree) fromBody(ctx context.Context, res gjson.Result) {
	prefix := helpers.LastElement(data.getPath()) + "."
	if res.Get(helpers.LastElement(data.getPath())).IsArray() {
		prefix += "0."
	}
	if value := res.Get(prefix + "Cisco-IOS-XE-spanning-tree:mode"); value.Exists() {
		data.Mode = types.StringValue(value.String())
	}
	if value := res.Get(prefix + "Cisco-IOS-XE-spanning-tree:loopguard.default"); value.Exists() {
		data.LoopguardDefault = types.BoolValue(true)
	} else {
		data.LoopguardDefault = types.BoolValue(false)
	}
	if value := res.Get(prefix + "Cisco-IOS-XE-spanning-tree:portfast.default"); value.Exists() {
		data.PortfastDefault = types.BoolValue(true)
	} else {
		data.PortfastDefault = types.BoolValue(false)
	}
	if value := res.Get(prefix + "Cisco-IOS-XE-spanning-tree:portfast.bpduguard.default"); value.Exists() {
		data.PortfastBpduguardDefault = types.BoolValue(true)
	} else {
		data.PortfastBpduguardDefault = types.BoolValue(false)
	}
	if value := res.Get(prefix + "Cisco-IOS-XE-spanning-tree:extend.system-id"); value.Exists() {
		data.ExtendSystemId = types.BoolValue(true)
	} else {
		data.ExtendSystemId = types.BoolValue(false)
	}
	if value := res.Get(prefix + "Cisco-IOS-XE-spanning-tree:mst.configuration.instance"); value.Exists() {
		data.MstInstances = make([]SpanningTreeMstInstances, 0)
		value.ForEach(func(k, v gjson.Result) bool {
			item := SpanningTreeMstInstances{}
			if cValue := v.Get("id"); cValue.Exists() {
				item.Id = types.Int64Value(cValue.Int())
			}
			if cValue := v.Get("vlan-ids"); cValue.Exists() {
				item.VlanIds = helpers.GetInt64List(cValue.Array())
			} else {
				item.VlanIds = types.ListNull(types.Int64Type)
			}
			data.MstInstances = append(data.MstInstances, item)
			return true
		})
	}
}

// End of section. //template:end fromBody

// Section below is generated&owned by "gen/generator.go". //template:begin fromBodyData

func (data *SpanningTreeData) fromBody(ctx context.Context, res gjson.Result) {
	prefix := helpers.LastElement(data.getPath()) + "."
	if res.Get(helpers.LastElement(data.getPath())).IsArray() {
		prefix += "0."
	}
	if value := res.Get(prefix + "Cisco-IOS-XE-spanning-tree:mode"); value.Exists() {
		data.Mode = types.StringValue(value.String())
	}
	if value := res.Get(prefix + "Cisco-IOS-XE-spanning-tree:loopguard.default"); value.Exists() {
		data.LoopguardDefault = types.BoolValue(true)
	} else {
		data.LoopguardDefault = types.BoolValue(false)
	}
	if value := res.Get(prefix + "Cisco-IOS-XE-spanning-tree:portfast.default"); value.Exists() {
		data.PortfastDefault = types.BoolValue(true)
	} else {
		data.PortfastDefault = types.BoolValue(false)
	}
	if value := res.Get(prefix + "Cisco-IOS-XE-spanning-tree:portfast.bpduguard.default"); value.Exists() {
		data.PortfastBpduguardDefault = types.BoolValue(true)
	} else {
		data.PortfastBpduguardDefault = types.BoolValue(false)
	}
	if value := res.Get(prefix + "Cisco-IOS-XE-spanning-tree:extend.system-id"); value.Exists() {
		data.ExtendSystemId = types.BoolValue(true)
	} else {
		data.ExtendSystemId = types.BoolValue(false)
	}
	if value := res.Get(prefix + "Cisco-IOS-XE-spanning-tree:mst.configuration.instance"); value.Exists() {
		data.MstInstances = make([]SpanningTreeMstInstances, 0)
		value.ForEach(func(k, v gjson.Result) bool {
			item := SpanningTreeMstInstances{}
			if cValue := v.Get("id"); cValue.Exists() {
				item.Id = types.Int64Value(cValue.Int())
			}
			if cValue := v.Get("vlan-ids"); cValue.Exists() {
				item.VlanIds = helpers.GetInt64List(cValue.Array())
			} else {
				item.VlanIds = types.ListNull(types.Int64Type)
			}
			data.MstInstances = append(data.MstInstances, item)
			return true
		})
	}
}

// End of section. //template:end fromBodyData

// Section below is generated&owned by "gen/generator.go". //template:begin getDeletedItems

func (data *SpanningTree) getDeletedItems(ctx context.Context, state SpanningTree) []string {
	deletedItems := make([]string, 0)
	for i := range state.MstInstances {
		stateKeyValues := [...]string{strconv.FormatInt(state.MstInstances[i].Id.ValueInt64(), 10)}

		emptyKeys := true
		if !reflect.ValueOf(state.MstInstances[i].Id.ValueInt64()).IsZero() {
			emptyKeys = false
		}
		if emptyKeys {
			continue
		}

		found := false
		for j := range data.MstInstances {
			found = true
			if state.MstInstances[i].Id.ValueInt64() != data.MstInstances[j].Id.ValueInt64() {
				found = false
			}
			if found {
				if !state.MstInstances[i].VlanIds.IsNull() {
					if data.MstInstances[j].VlanIds.IsNull() {
						deletedItems = append(deletedItems, fmt.Sprintf("%v/Cisco-IOS-XE-spanning-tree:mst/configuration/instance=%v/vlan-ids", state.getPath(), strings.Join(stateKeyValues[:], ",")))
					} else {
						var dataValues, stateValues []int
						data.MstInstances[i].VlanIds.ElementsAs(ctx, &dataValues, false)
						state.MstInstances[j].VlanIds.ElementsAs(ctx, &stateValues, false)
						for _, v := range stateValues {
							found := false
							for _, vv := range dataValues {
								if v == vv {
									found = true
									break
								}
							}
							if !found {
								deletedItems = append(deletedItems, fmt.Sprintf("%v/Cisco-IOS-XE-spanning-tree:mst/configuration/instance=%v/vlan-ids=%v", state.getPath(), strings.Join(stateKeyValues[:], ","), v))
							}
						}
					}
				}
				break
			}
		}
		if !found {
			deletedItems = append(deletedItems, fmt.Sprintf("%v/Cisco-IOS-XE-spanning-tree:mst/configuration/instance=%v", state.getPath(), strings.Join(stateKeyValues[:], ",")))
		}
	}
	if !state.PortfastBpduguardDefault.IsNull() && data.PortfastBpduguardDefault.IsNull() {
		deletedItems = append(deletedItems, fmt.Sprintf("%v/Cisco-IOS-XE-spanning-tree:portfast/bpduguard/default", state.getPath()))
	}
	if !state.PortfastDefault.IsNull() && data.PortfastDefault.IsNull() {
		deletedItems = append(deletedItems, fmt.Sprintf("%v/Cisco-IOS-XE-spanning-tree:portfast/default", state.getPath()))
	}
	if !state.LoopguardDefault.IsNull() && data.LoopguardDefault.IsNull() {
		deletedItems = append(deletedItems, fmt.Sprintf("%v/Cisco-IOS-XE-spanning-tree:loopguard/default", state.getPath()))
	}
	if !state.Mode.IsNull() && data.Mode.IsNull() {
		deletedItems = append(deletedItems, fmt.Sprintf("%v/Cisco-IOS-XE-spanning-tree:mode", state.getPath()))
	}

	return deletedItems
}

// End of section. //template:end getDeletedItems

// Section below is generated&owned by "gen/generator.go". //template:begin getEmptyLeafsDelete

func (data *SpanningTree) getEmptyLeafsDelete(ctx context.Context) []string {
	emptyLeafsDelete := make([]string, 0)

	if !data.ExtendSystemId.IsNull() && !data.ExtendSystemId.ValueBool() {
		emptyLeafsDelete = append(emptyLeafsDelete, fmt.Sprintf("%v/Cisco-IOS-XE-spanning-tree:extend/system-id", data.getPath()))
	}
	if !data.PortfastBpduguardDefault.IsNull() && !data.PortfastBpduguardDefault.ValueBool() {
		emptyLeafsDelete = append(emptyLeafsDelete, fmt.Sprintf("%v/Cisco-IOS-XE-spanning-tree:portfast/bpduguard/default", data.getPath()))
	}
	if !data.PortfastDefault.IsNull() && !data.PortfastDefault.ValueBool() {
		emptyLeafsDelete = append(emptyLeafsDelete, fmt.Sprintf("%v/Cisco-IOS-XE-spanning-tree:portfast/default", data.getPath()))
	}
	if !data.LoopguardDefault.IsNull() && !data.LoopguardDefault.ValueBool() {
		emptyLeafsDelete = append(emptyLeafsDelete, fmt.Sprintf("%v/Cisco-IOS-XE-spanning-tree:loopguard/default", data.getPath()))
	}

	return emptyLeafsDelete
}

// End of section. //template:end getEmptyLeafsDelete

// Section below is generated&owned by "gen/generator.go". //template:begin getDeletePaths

func (data *SpanningTree) getDeletePaths(ctx context.Context) []string {
	var deletePaths []string
	for i := range data.MstInstances {
		keyValues := [...]string{strconv.FormatInt(data.MstInstances[i].Id.ValueInt64(), 10)}

		deletePaths = append(deletePaths, fmt.Sprintf("%v/Cisco-IOS-XE-spanning-tree:mst/configuration/instance=%v", data.getPath(), strings.Join(keyValues[:], ",")))
	}
	if !data.PortfastBpduguardDefault.IsNull() {
		deletePaths = append(deletePaths, fmt.Sprintf("%v/Cisco-IOS-XE-spanning-tree:portfast/bpduguard/default", data.getPath()))
	}
	if !data.PortfastDefault.IsNull() {
		deletePaths = append(deletePaths, fmt.Sprintf("%v/Cisco-IOS-XE-spanning-tree:portfast/default", data.getPath()))
	}
	if !data.LoopguardDefault.IsNull() {
		deletePaths = append(deletePaths, fmt.Sprintf("%v/Cisco-IOS-XE-spanning-tree:loopguard/default", data.getPath()))
	}
	if !data.Mode.IsNull() {
		deletePaths = append(deletePaths, fmt.Sprintf("%v/Cisco-IOS-XE-spanning-tree:mode", data.getPath()))
	}

	return deletePaths
}

// End of section. //template:end getDeletePaths
