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

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

func resourceStaticRouteCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceStaticRouteCreate: called for vins_id %s", d.Get("vins_id"))

	c := m.(*controller.ControllerCfg)

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

	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),
	}

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

	staticRouteData, err := getStaticRouteData(ctx, d, m)
	if err != nil {
		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 {
	log.Debugf("resourceStaticRouteRead: called for route_id %s", d.Id())

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

	flattenStaticRouteData(d, staticRouteData)

	return nil
}

func resourceStaticRouteUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	return nil
}

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

	c := m.(*controller.ControllerCfg)
	req := vins.StaticRouteDelRequest{}

	arr := strings.Split(d.Id(), "#")
	if len(arr) != 2 {
		return diag.Errorf("broken state id - %s", d.Id())
	}

	req.VINSID, _ = strconv.ParseUint(arr[0], 10, 64)
	req.RouteId, _ = strconv.ParseUint(arr[1], 10, 64)

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

	d.SetId("")

	return nil
}

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(),
	}
}
