/*
Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved.
Authors:
Petr Krutov, <petr.krutov@digitalenergy.online>
Stanislav Solovev, <spsolovev@digitalenergy.online>

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 segments

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/segments"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
)

func resourceSegmentCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceSegmentCreate: called segment with name %s",
		d.Get("display_name").(string))
	c := m.(*controller.ControllerCfg)

	subnetV4, v4ok := d.GetOk("subnet_v4")
	subnetV6, v6ok := d.GetOk("subnet_v6")

	if !v4ok && !v6ok {
		return diag.Errorf("resourceSegmentCreate: either subnet_v4 or subnet_v6 must be specified")
	}

	req := segments.CreateRequest{
		AccessGroupID: d.Get("access_group_id").(string),
		Description:   d.Get("description").(string),
		DisplayName:   d.Get("display_name").(string),
		Enabled:       d.Get("enabled").(bool),
	}

	if t, ok := d.GetOk("type"); ok {
		req.Type = t.(string)
	}

	if v4ok {
		req.SubnetV4 = subnetV4.(string)
	}

	if v6ok {
		req.SubnetV6 = subnetV6.(string)
	}

	if dhcpV4, ok := d.GetOk("dhcp_v4"); ok {
		dhcpV4 := dhcpV4.([]interface{})[0]
		dhcpV4Map := dhcpV4.(map[string]interface{})
		dhcpReq := segments.DHCPv4ConfigRequest{
			Gateway:  dhcpV4Map["gateway"].(string),
			ServerIP: dhcpV4Map["server_ip"].(string),
			Enabled:  dhcpV4Map["enabled"].(bool),
		}
		serverMAC, sMAC := dhcpV4Map["server_mac"]
		if sMAC {
			dhcpReq.ServerMAC = serverMAC.(string)
		}

		leaseTime, lTime := dhcpV4Map["lease_time"]
		if lTime {
			dhcpReq.LeaseTime = uint64(leaseTime.(int))
		}

		dns, dnsOk := dhcpV4Map["dns"]
		if dnsOk {
			dnsArr := make([]string, 0)
			for _, v := range dns.([]interface{}) {
				dnsArr = append(dnsArr, v.(string))
			}
			dhcpReq.DNS = dnsArr
		}

		adrRanges, earOK := dhcpV4Map["excluded_address_ranges"]
		if earOK {
			earArr := make([]string, 0)
			for _, v := range adrRanges.([]interface{}) {
				earArr = append(earArr, v.(string))
			}
			dhcpReq.ExcludedAddressRanges = earArr
		}
		req.DHCPv4 = &dhcpReq
	}

	if dhcpV6, ok := d.GetOk("dhcp_v6"); ok {
		dhcpV6 := dhcpV6.([]interface{})[0]
		dhcpV6Map := dhcpV6.(map[string]interface{})
		dhcpReq := segments.DHCPv6ConfigRequest{
			AddressPrefix: dhcpV6Map["address_prefix"].(string),
			Enabled:       dhcpV6Map["enabled"].(bool),
		}
		serverMAC, sMAC := dhcpV6Map["server_mac"]
		if sMAC {
			dhcpReq.ServerMAC = serverMAC.(string)
		}

		leaseTime, lTime := dhcpV6Map["lease_time"]
		if lTime {
			dhcpReq.LeaseTime = uint64(leaseTime.(int))
		}

		dns, dnsOk := dhcpV6Map["dns"]
		if dnsOk {
			dnsArr := make([]string, 0)
			for _, v := range dns.([]interface{}) {
				dnsArr = append(dnsArr, v.(string))
			}
			dhcpReq.DNS = dnsArr
		}
		req.DHCPv6 = &dhcpReq
	}

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

	d.SetId(segmentData.ID)
	d.Set("segment_id", segmentData.ID)

	return append(resourceSegmentRead(ctx, d, m))
}

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

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

	flattenSegment(d, segmentData)

	return nil
}

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

	c := m.(*controller.ControllerCfg)

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

	subnetV4, v4ok := d.GetOk("subnet_v4")
	subnetV6, v6ok := d.GetOk("subnet_v6")

	if !v4ok && !v6ok {
		return diag.Errorf("resourceSegmentCreate: either subnet_v4 or subnet_v6 must be specified")
	}

	needUpdate := false

	req := segments.UpdateRequest{
		SegmentID:     segmentData.ID,
		VersionID:     segmentData.VersionID,
		AccessGroupID: d.Get("access_group_id").(string),
		Description:   d.Get("description").(string),
		DisplayName:   d.Get("display_name").(string),
		Enabled:       d.Get("enabled").(bool),
	}

	if d.HasChanges("access_group_id", "description", "display_name", "enabled", "type") {
		needUpdate = true
	}

	if t, ok := d.GetOk("type"); ok {
		req.Type = t.(string)
	}

	if v4ok {
		req.SubnetV4 = subnetV4.(string)
	}

	if v6ok {
		req.SubnetV6 = subnetV6.(string)
	}

	if d.HasChange("dhcp_v4") {
		if dhcpV4, ok := d.GetOk("dhcp_v4"); ok {
			dhcpV4 := dhcpV4.([]interface{})[0]
			dhcpV4Map := dhcpV4.(map[string]interface{})
			dhcpReq := segments.DHCPv4ConfigRequest{
				Gateway:  dhcpV4Map["gateway"].(string),
				ServerIP: dhcpV4Map["server_ip"].(string),
				Enabled:  dhcpV4Map["enabled"].(bool),
			}
			serverMAC, sMAC := dhcpV4Map["server_mac"]
			if sMAC {
				dhcpReq.ServerMAC = serverMAC.(string)
			}

			leaseTime, lTime := dhcpV4Map["lease_time"]
			if lTime {
				dhcpReq.LeaseTime = uint64(leaseTime.(int))
			}

			dns, dnsOk := dhcpV4Map["dns"]
			if dnsOk {
				dnsArr := make([]string, 0)
				for _, v := range dns.([]interface{}) {
					dnsArr = append(dnsArr, v.(string))
				}
				dhcpReq.DNS = dnsArr
			}

			adrRanges, earOK := dhcpV4Map["excluded_address_ranges"]
			if earOK {
				earArr := make([]string, 0)
				for _, v := range adrRanges.([]interface{}) {
					earArr = append(earArr, v.(string))
				}
				dhcpReq.ExcludedAddressRanges = earArr
			}
			req.DHCPv4 = &dhcpReq
		}

		needUpdate = true
	}

	if d.HasChange("dhcp_v6") {
		if dhcpV6, ok := d.GetOk("dhcp_v6"); ok {
			dhcpV6 := dhcpV6.([]interface{})[0]
			dhcpV6Map := dhcpV6.(map[string]interface{})
			dhcpReq := segments.DHCPv6ConfigRequest{
				AddressPrefix: dhcpV6Map["address_prefix"].(string),
				Enabled:       dhcpV6Map["enabled"].(bool),
			}
			serverMAC, sMAC := dhcpV6Map["server_mac"]
			if sMAC {
				dhcpReq.ServerMAC = serverMAC.(string)
			}

			leaseTime, lTime := dhcpV6Map["lease_time"]
			if lTime {
				dhcpReq.LeaseTime = uint64(leaseTime.(int))
			}

			dns, dnsOk := dhcpV6Map["dns"]
			if dnsOk {
				dnsArr := make([]string, 0)
				for _, v := range dns.([]interface{}) {
					dnsArr = append(dnsArr, v.(string))
				}
				dhcpReq.DNS = dnsArr
			}
			req.DHCPv6 = &dhcpReq
		}
		needUpdate = true
	}

	if needUpdate {
		segmentData, err = c.SDN().Segments().Update(ctx, req)
	}

	if err != nil {
		d.SetId("")
		return diag.FromErr(err)
	}

	d.SetId(segmentData.ID)
	d.Set("segment_id", segmentData.ID)

	return append(resourceSegmentRead(ctx, d, m))
}

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

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

	req := segments.DeleteRequest{
		SegmentID: segmentData.ID,
		VersionID: segmentData.VersionID,
	}

	if force, ok := d.GetOk("force"); ok {
		req.Force = force.(bool)
	}

	c := m.(*controller.ControllerCfg)
	err = c.SDN().Segments().Delete(ctx, req)
	if err != nil {
		return diag.FromErr(err)
	}

	d.SetId("")

	return nil
}

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

		CreateContext: resourceSegmentCreate,
		ReadContext:   resourceSegmentRead,
		UpdateContext: resourceSegmentUpdate,
		DeleteContext: resourceSegmentDelete,

		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("updated_at")
				diff.SetNewComputed("version_id")
			}
			return nil
		},

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

		Schema: resourceSegmentSchemaMake(),
	}
}
