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

import (
	"context"
	"fmt"
	"strconv"
	"strings"

	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/vins"
	"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"

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

func resourceStaticRouteCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	c := m.(*controller.ControllerCfg)

	if _, ok := d.GetOk("vins_id"); ok {
		haveVinsID, err := existVinsID(ctx, d, m)
		if err != nil {
			return diag.FromErr(err)
		}

		if !haveVinsID {
			return diag.Errorf("resourceStaticRouteCreate: can't create Static Route because Vins ID %d is not allowed or does not exist", d.Get("vins_id").(int))
		}
	}

	req := vins.StaticRouteAddRequest{
		VINSID:      uint64(d.Get("vins_id").(int)),
		Destination: d.Get("destination").(string),
		Netmask:     d.Get("netmask").(string),
		Gateway:     d.Get("gateway").(string),
	}

	if computesIDS, ok := d.GetOk("compute_ids"); ok {
		ids := computesIDS.([]interface{})

		res := make([]uint64, 10)

		for _, id := range ids {
			computeId := uint64(id.(int))
			res = append(res, computeId)
		}

		req.ComputeIds = res
	}

	_, err := c.CloudAPI().VINS().StaticRouteAdd(ctx, req)
	if err != nil {
		return diag.FromErr(err)
	}

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

	d.SetId(fmt.Sprintf("%d#%d", req.VINSID, staticRouteData.ID))

	return resourceStaticRouteRead(ctx, d, m)
}

func resourceStaticRouteRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	warnings := dc.Warnings{}

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

	flattenStaticRouteData(d, staticRouteData)

	return warnings.Get()
}

func resourceStaticRouteUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	c := m.(*controller.ControllerCfg)
	warnings := dc.Warnings{}

	if _, ok := d.GetOk("vins_id"); ok {
		haveVinsID, err := existVinsID(ctx, d, m)
		if err != nil {
			return diag.FromErr(err)
		}

		if !haveVinsID {
			return diag.Errorf("resourceVinsUpdate: can't update Static Route because VinsID %d is not allowed or does not exist", d.Get("vins_id").(int))
		}
	}

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

	if d.HasChange("compute_ids") {
		deletedIds := make([]uint64, 0)
		addedIds := make([]uint64, 0)

		oldComputeIds, newComputeIds := d.GetChange("compute_ids")
		oldComputeIdsSlice := oldComputeIds.([]interface{})
		newComputeIdsSlice := newComputeIds.([]interface{})

		for _, el := range oldComputeIdsSlice {
			if !isContainsIds(newComputeIdsSlice, el) {
				convertedEl := uint64(el.(int))
				deletedIds = append(deletedIds, convertedEl)
			}
		}

		for _, el := range newComputeIdsSlice {
			if !isContainsIds(oldComputeIdsSlice, el) {
				convertedEl := uint64(el.(int))
				addedIds = append(addedIds, convertedEl)
			}
		}

		if len(deletedIds) > 0 {
			req := vins.StaticRouteAccessRevokeRequest{
				VINSID:     uint64(d.Get("vins_id").(int)),
				RouteId:    staticRouteData.ID,
				ComputeIds: deletedIds,
			}

			_, err := c.CloudAPI().VINS().StaticRouteAccessRevoke(ctx, req)
			if err != nil {
				warnings.Add(err)
			}
		}

		if len(addedIds) > 0 {
			req := vins.StaticRouteAccessGrantRequest{
				VINSID:     uint64(d.Get("vins_id").(int)),
				RouteId:    staticRouteData.ID,
				ComputeIds: addedIds,
			}

			_, err := c.CloudAPI().VINS().StaticRouteAccessGrant(ctx, req)
			if err != nil {
				warnings.Add(err)
			}
		}
	}

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

func resourceStaticRouteDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	c := m.(*controller.ControllerCfg)
	arr := strings.Split(d.Id(), "#")
	if len(arr) != 2 {
		return diag.FromErr(fmt.Errorf("broken state id"))
	}

	vinsId, _ := strconv.ParseUint(arr[0], 10, 64)
	routeId, _ := strconv.ParseUint(arr[1], 10, 64)

	req := vins.StaticRouteDelRequest{
		VINSID:  vinsId,
		RouteId: routeId,
	}

	_, err := c.CloudAPI().VINS().StaticRouteDel(ctx, req)
	if err != nil {
		return diag.FromErr(err)
	}

	d.SetId("")

	return nil
}

func resourceStaticRouteSchemaMake() map[string]*schema.Schema {
	rets := dataSourceStaticRouteSchemaMake()
	rets["route_id"] = &schema.Schema{
		Type:     schema.TypeInt,
		Computed: true,
		Optional: true,
	}
	rets["compute_ids"] = &schema.Schema{
		Type:     schema.TypeList,
		Optional: true,
		Computed: true,
		Elem: &schema.Schema{
			Type: schema.TypeInt,
		},
	}
	rets["destination"] = &schema.Schema{
		Type:     schema.TypeString,
		Required: true,
	}

	rets["gateway"] = &schema.Schema{
		Type:     schema.TypeString,
		Required: true,
	}
	rets["netmask"] = &schema.Schema{
		Type:     schema.TypeString,
		Required: true,
	}

	return rets
}

func isContainsIds(els []interface{}, el interface{}) bool {
	convEl := el.(int)
	for _, elOld := range els {
		if convEl == elOld.(int) {
			return true
		}
	}
	return false
}

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

		CreateContext: resourceStaticRouteCreate,
		ReadContext:   resourceStaticRouteRead,
		UpdateContext: resourceStaticRouteUpdate,
		DeleteContext: resourceStaticRouteDelete,

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

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

		Schema: resourceStaticRouteSchemaMake(),
	}
}
