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

import (
	"context"

	"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
	log "github.com/sirupsen/logrus"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/sdn/netobjgroups"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
)

func resourceNetworkObjectGroupCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceNetworkObjectGroupCreate: called with name %s", d.Get("name").(string))

	c := m.(*controller.ControllerCfg)

	req := netobjgroups.CreateRequest{
		AccessGroupID: d.Get("access_group_id").(string),
		Description:   d.Get("description").(string),
		Name:          d.Get("name").(string),
	}

	if addrRaw, ok := d.GetOk("addresses"); ok {
		req.Addresses = buildAddressesRequest(addrRaw.([]interface{}))
	}

	if l2Raw, ok := d.GetOk("l2_connection_ports_bindings"); ok {
		req.L2ConnectionPortsBindings = buildL2PortsBindingsRequest(l2Raw.([]interface{}))
	}

	rec, err := c.SDN().NetworkObjectGroups().Create(ctx, req)
	if err != nil {
		d.SetId("")
		return diag.FromErr(err)
	}

	d.SetId(rec.ID)

	return resourceNetworkObjectGroupRead(ctx, d, m)
}

func resourceNetworkObjectGroupRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceNetworkObjectGroupRead: called with id %s", d.Id())

	rec, err := utilityNetworkObjectGroupCheckPresence(ctx, d, m)
	if err != nil {
		d.SetId("")
		return diag.FromErr(err)
	}

	flattenNetworkObjectGroupResource(d, rec)
	d.SetId(rec.ID)

	return nil
}

func resourceNetworkObjectGroupUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceNetworkObjectGroupUpdate: called with id %s", d.Id())

	c := m.(*controller.ControllerCfg)

	req := netobjgroups.UpdateRequest{
		ObjectGroupID: d.Id(),
		VersionID:     uint64(d.Get("version_id").(int)),
		AccessGroupID: d.Get("access_group_id").(string),
		Description:   d.Get("description").(string),
		Name:          d.Get("name").(string),
	}

	if addrRaw, ok := d.GetOk("addresses"); ok {
		req.Addresses = buildAddressesRequest(addrRaw.([]interface{}))
	}

	rec, err := c.SDN().NetworkObjectGroups().Update(ctx, req)
	if err != nil {
		return diag.FromErr(err)
	}

	d.SetId(rec.ID)

	return resourceNetworkObjectGroupRead(ctx, d, m)
}

func resourceNetworkObjectGroupDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceNetworkObjectGroupDelete: called with id %s", d.Id())

	c := m.(*controller.ControllerCfg)

	req := netobjgroups.DeleteRequest{
		ObjectGroupID: d.Id(),
		VersionID:     uint64(d.Get("version_id").(int)),
	}

	_, err := c.SDN().NetworkObjectGroups().Delete(ctx, req)
	if err != nil {
		return diag.FromErr(err)
	}

	d.SetId("")
	return nil
}

func buildL2PortsBindingsRequest(raw []interface{}) []netobjgroups.LogicalPortsBindings {
	result := make([]netobjgroups.LogicalPortsBindings, 0, len(raw))
	for _, item := range raw {
		m := item.(map[string]interface{})
		result = append(result, netobjgroups.LogicalPortsBindings{
			PortID:      m["port_id"].(string),
			PortVersion: uint64(m["port_version"].(int)),
		})
	}
	return result
}

func buildAddressesRequest(raw []interface{}) []netobjgroups.NetAddressRequest {
	result := make([]netobjgroups.NetAddressRequest, 0, len(raw))
	for _, item := range raw {
		addrMap := item.(map[string]interface{})
		addr := netobjgroups.NetAddressRequest{
			NetAddressType: addrMap["net_address_type"].(string),
		}
		if v, ok := addrMap["ip_addr"].(string); ok && v != "" {
			addr.IPAddr = v
		}
		if v, ok := addrMap["ip_addr_range_end"].(string); ok && v != "" {
			addr.IPAddrRangeEnd = v
		}
		if v, ok := addrMap["ip_prefix"].(string); ok && v != "" {
			addr.IPPrefix = v
		}
		if v, ok := addrMap["mac_addr"].(string); ok && v != "" {
			addr.MACAddr = v
		}
		result = append(result, addr)
	}
	return result
}

func resourceNetworkObjectGroupSchemaMake() map[string]*schema.Schema {
	return map[string]*schema.Schema{
		"name": {
			Type:     schema.TypeString,
			Required: true,
		},
		"access_group_id": {
			Type:     schema.TypeString,
			Required: true,
		},
		"description": {
			Type:     schema.TypeString,
			Required: true,
		},
		"addresses": {
			Type:     schema.TypeList,
			Optional: true,
			Computed: true,
			Elem: &schema.Resource{
				Schema: map[string]*schema.Schema{
					"id": {
						Type:     schema.TypeString,
						Computed: true,
					},
					"net_address_type": {
						Type:     schema.TypeString,
						Required: true,
					},
					"ip_addr": {
						Type:     schema.TypeString,
						Optional: true,
						Computed: true,
					},
					"ip_addr_range_end": {
						Type:     schema.TypeString,
						Optional: true,
						Computed: true,
					},
					"ip_prefix": {
						Type:     schema.TypeString,
						Optional: true,
						Computed: true,
					},
					"mac_addr": {
						Type:     schema.TypeString,
						Optional: true,
						Computed: true,
					},
				},
			},
		},
		"l2_connection_ports_bindings": {
			Type:     schema.TypeList,
			Optional: true,
			Elem: &schema.Resource{
				Schema: map[string]*schema.Schema{
					"port_id": {
						Type:     schema.TypeString,
						Required: true,
					},
					"port_version": {
						Type:     schema.TypeInt,
						Required: true,
					},
				},
			},
		},
		"access_group_name": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"type": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"purpose": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"version_id": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"counters": {
			Type:     schema.TypeList,
			Computed: true,
			Elem: &schema.Resource{
				Schema: map[string]*schema.Schema{
					"addresses_count": {
						Type:     schema.TypeInt,
						Computed: true,
					},
					"l2_connection_ports_count": {
						Type:     schema.TypeInt,
						Computed: true,
					},
					"logical_ports_count": {
						Type:     schema.TypeInt,
						Computed: true,
					},
					"security_policies_count": {
						Type:     schema.TypeInt,
						Computed: true,
					},
					"security_rules_count": {
						Type:     schema.TypeInt,
						Computed: true,
					},
				},
			},
		},
		"l2_connection_ports":    l2ConnectionPortsComputedSchema(),
		"logical_ports":          logicalPortsComputedSchema(),
		"external_network_ports": externalNetworkPortsComputedSchema(),
		"security_policies":      securityPoliciesComputedSchema(),
	}
}

func ResourceNetworkObjectGroup() *schema.Resource {
	return &schema.Resource{
		SchemaVersion: 1,

		CreateContext: resourceNetworkObjectGroupCreate,
		ReadContext:   resourceNetworkObjectGroupRead,
		UpdateContext: resourceNetworkObjectGroupUpdate,
		DeleteContext: resourceNetworkObjectGroupDelete,

		Importer: &schema.ResourceImporter{
			StateContext: schema.ImportStatePassthroughContext,
		},

		CustomizeDiff: func(ctx context.Context, diff *schema.ResourceDiff, i interface{}) error {
			changedKeys := diff.GetChangedKeysPrefix("")
			if len(changedKeys) > 0 {
				diff.SetNewComputed("version_id")
			}
			return nil
		},

		Timeouts: &schema.ResourceTimeout{
			Create:  &constants.Timeout600s,
			Read:    &constants.Timeout300s,
			Update:  &constants.Timeout600s,
			Delete:  &constants.Timeout300s,
			Default: &constants.Timeout300s,
		},

		Schema: resourceNetworkObjectGroupSchemaMake(),
	}
}
