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

import (
	"context"
	"strconv"

	dpdk "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/dpdknet"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/dc"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/status"

	"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
	log "github.com/sirupsen/logrus"
)

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

	if diags := checkParamsExistence(ctx, d, c); diags != nil {
		return diags
	}

	req := dpdk.CreateRequest{
		Name:      d.Get("name").(string),
		GID:       uint64(d.Get("gid").(int)),
		VlanID:    uint64(d.Get("vlan_id").(int)),
		OVSBridge: d.Get("ovs_bridge").(string),
	}

	if desc, ok := d.GetOk("desc"); ok {
		req.Description = desc.(string)
	}

	if accountAccess, ok := d.GetOk("account_access"); ok {
		IDs := accountAccess.([]interface{})
		for _, ID := range IDs {
			req.AccountAccess = append(req.AccountAccess, uint64(ID.(int)))
		}
	}
	if rgAccess, ok := d.GetOk("rg_access"); ok {
		IDs := rgAccess.([]interface{})
		for _, ID := range IDs {
			req.RGAccess = append(req.RGAccess, uint64(ID.(int)))
		}
	}

	req.EnableSecGroups = d.Get("enable_secgroups").(bool)

	dpdkID, err := c.CloudBroker().DPDKNet().Create(ctx, req)
	if err != nil {
		d.SetId("")
		return diag.FromErr(err)
	}

	d.SetId(strconv.FormatUint(dpdkID, 10))
	d.Set("dpdk_id", dpdkID)

	warnings := dc.Warnings{}

	if err = utilityDPDKNetEnabled(ctx, d, m); err != nil {
		warnings.Add(err)
	}

	return append(warnings.Get(), resourceDPDKNetRead(ctx, d, m)...)
}

func resourceDPDKNetRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceDPDKNetRead: called for pdpk_id %d", d.Get("dpdk_id").(int))
	w := dc.Warnings{}

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

	log.Debugf("status: %s", dpdkItem.Status)

	switch dpdkItem.Status {
	case status.Destroyed, status.Purged:
		d.Set("dpdk_id", 0)
		d.SetId("")
		return diag.Errorf("The resource cannot be read because it has been destroyed")
	case status.Deleted:
	case status.Assigned:
	case status.Modeled:
		return diag.Errorf("The DPDK network is in status: %s, please, contact support for more information", dpdkItem.Status)
	case status.Creating:
	case status.Created:
	case status.Allocated:
	case status.Unallocated:
	}

	flattenDPDKNet(d, dpdkItem)

	return w.Get()
}

func resourceDPDKNetUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceDPDKNetUpdate: called for dpdk_id %d", d.Get("dpdk_id").(int))
	c := m.(*controller.ControllerCfg)
	w := dc.Warnings{}

	if diags := checkParamsExistence(ctx, d, c); diags != nil {
		return diags
	}

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

	switch dpdkItem.Status {
	case status.Destroyed, status.Purged:
		d.Set("dpdk_id", 0)
		d.SetId("")
		return diag.Errorf("The resource cannot be updated because it has been destroyed")
	case status.Deleted:
		d.Set("dpdk_id", 0)
		d.SetId("")
		return diag.Errorf("The resource cannot be updated because it has been deleted")
	case status.Assigned:
	case status.Modeled:
		return diag.Errorf("The DPDK network is in status: %s, please, contact support for more information", dpdkItem.Status)
	case status.Creating:
	case status.Created:
	case status.Allocated:
	case status.Unallocated:
	}

	if d.HasChange("enabled") {
		if err := utilityDPDKNetEnabled(ctx, d, m); err != nil {
			return diag.FromErr(err)
		}
	}

	if d.HasChanges("name", "desc", "vlan_id", "ovs_bridge", "account_access", "rg_access", "enable_secgroups") {
		if err := utilityDPDKNetUpdate(ctx, d, m); err != nil {
			return diag.FromErr(err)
		}
	}

	return append(w.Get(), resourceDPDKNetRead(ctx, d, m)...)
}

func resourceDPDKNetDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceDPDKNetDelete: called for dpdk_id %d", d.Get("dpdk_id").(int))
	c := m.(*controller.ControllerCfg)

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

	req := dpdk.DeleteRequest{
		DPDKID: dpdkItem.ID,
	}

	if d.Get("enabled") == true {
		req := dpdk.DisableRequest{
			DPDKID: dpdkItem.ID,
		}

		if _, err := c.CloudBroker().DPDKNet().Disable(ctx, req); err != nil {
			return diag.FromErr(err)
		}
	}

	_, err = c.CloudBroker().DPDKNet().Delete(ctx, req)
	if err != nil {
		return diag.FromErr(err)
	}

	d.SetId("")

	return nil
}

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

		CreateContext: resourceDPDKNetCreate,
		ReadContext:   resourceDPDKNetRead,
		UpdateContext: resourceDPDKNetUpdate,
		DeleteContext: resourceDPDKNetDelete,

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

		CustomizeDiff: func(ctx context.Context, diff *schema.ResourceDiff, i interface{}) error {
			if diff.HasChange("enable") {
				diff.SetNewComputed("status")
			}
			if diff.HasChanges() {
				diff.SetNewComputed("updated_time")
			}
			return nil
		},

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

		Schema: resourceDPDKNetSchemaMake(),
	}
}
