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

	log "github.com/sirupsen/logrus"
	"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"
	"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"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
)

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

	if _, ok := d.GetOk("rg_id"); ok {
		haveRGID, err := existRGID(ctx, d, m)
		if err != nil {
			return diag.FromErr(err)
		}

		if !haveRGID {
			return diag.Errorf("resourceVinsCreate: can't create ViNS because RGID %d is not allowed or does not exist", d.Get("rg_id").(int))
		}
	}

	if _, ok := d.GetOk("ext_net_id"); ok {
		haveExtNetID, err := existExtNetID(ctx, d, m)
		if err != nil {
			return diag.FromErr(err)
		}

		if !haveExtNetID {
			return diag.Errorf("resourceVinsCreate: can't create ViNS because ExtNetID %d is not allowed or does not exist", d.Get("ext_net_id").(int))
		}
	}

	if _, ok := d.GetOk("account_id"); ok {
		haveAccountID, err := existAccountID(ctx, d, m)
		if err != nil {
			return diag.FromErr(err)
		}

		if !haveAccountID {
			return diag.Errorf("resourceVinsCreate: can't create ViNS because AccountID %d is not allowed or does not exist", d.Get("account_id").(int))
		}
	}

	if _, ok := d.GetOk("gid"); ok {
		haveGID, err := existGID(ctx, d, m)
		if err != nil {
			return diag.FromErr(err)
		}

		if !haveGID {
			return diag.Errorf("resourceVinsCreate: can't create ViNS because GID %d is not allowed or does not exist", d.Get("gid").(int))
		}
	}

	rgId, rgOk := d.GetOk("rg_id")
	accountId, accountIdOk := d.GetOk("account_id")
	if !rgOk && !accountIdOk {
		return diag.Errorf("resourceVinsCreate: no valid accountId or resource group ID specified")
	}

	if rgOk {
		req := vins.CreateInRGRequest{
			Name: d.Get("name").(string),
			RGID: uint64(rgId.(int)),
		}

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

		//extnet v1
		req.ExtNetID = int64(d.Get("ext_net_id").(int))
		if extIp, ok := d.GetOk("ext_ip_addr"); ok {
			req.ExtIP = extIp.(string)
		}

		//extnet v2
		if extNetResp, ok := d.GetOk("ext_net"); ok {
			extNetSl := extNetResp.([]interface{})
			extNet := extNetSl[0].(map[string]interface{})

			req.ExtNetID = int64(extNet["ext_net_id"].(int))
			req.ExtIP = extNet["ext_net_ip"].(string)
		}

		if desc, ok := d.GetOk("desc"); ok {
			req.Description = desc.(string)
		}
		if preReservationsNum, ok := d.GetOk("pre_reservations_num"); ok {
			req.PreReservationsNum = uint64(preReservationsNum.(int))
		}
		if dns, ok := d.GetOk("dns"); ok {
			dnsInterface := dns.(*schema.Set).List()
			req.DNSList = make([]string, 0, len(dnsInterface))
			for _, item := range dnsInterface {
				req.DNSList = append(req.DNSList, item.(string))
			}
		}

		if zoneID, ok := d.GetOk("zone_id"); ok {
			req.ZoneID = uint64(zoneID.(int))
		}

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

		id, err := c.CloudAPI().VINS().CreateInRG(ctx, req)
		if err != nil {
			d.SetId("")
			return diag.FromErr(err)
		}

		d.SetId(strconv.FormatUint(id, 10))
	} else if accountIdOk {
		req := vins.CreateInAccountRequest{
			Name:      d.Get("name").(string),
			AccountID: uint64(accountId.(int)),
		}

		if gid, ok := d.GetOk("gid"); ok {
			req.GID = uint64(gid.(int))
		}
		if ipcidr, ok := d.GetOk("ipcidr"); ok {
			req.IPCIDR = ipcidr.(string)
		}
		if desc, ok := d.GetOk("desc"); ok {
			req.Description = desc.(string)
		}
		if preReservationsNum, ok := d.GetOk("pre_reservations_num"); ok {
			req.PreReservationsNum = uint64(preReservationsNum.(int))
		}
		if dns, ok := d.GetOk("dns"); ok {
			dnsInterface := dns.(*schema.Set).List()
			req.DNSList = make([]string, 0, len(dnsInterface))
			for _, item := range dnsInterface {
				req.DNSList = append(req.DNSList, item.(string))
			}
		}

		if zoneID, ok := d.GetOk("zone_id"); ok {
			req.ZoneID = uint64(zoneID.(int))
		}

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

		id, err := c.CloudAPI().VINS().CreateInAccount(ctx, req)
		if err != nil {
			d.SetId("")
			return diag.FromErr(err)
		}

		d.SetId(strconv.FormatUint(id, 10))
	}

	vinsId, _ := strconv.ParseUint(d.Id(), 10, 64)

	warnings := dc.Warnings{}
	if ipRes, ok := d.GetOk("ip"); ok {
		ipsSlice := ipRes.([]interface{})
		for _, ipInterfase := range ipsSlice {
			ip := ipInterfase.(map[string]interface{})

			req := vins.IPReserveRequest{
				VINSID: vinsId,
				Type:   ip["type"].(string),
			}

			if ipAddr, ok := ip["ip_addr"]; ok {
				req.IPAddr = ipAddr.(string)
			}
			if macAddr, ok := ip["mac_addr"]; ok {
				req.MAC = macAddr.(string)
			}
			if computeId, ok := ip["compute_id"]; ok {
				req.ComputeID = uint64(computeId.(int))
			}
			_, err := c.CloudAPI().VINS().IPReserve(ctx, req)
			if err != nil {
				warnings.Add(err)
			}
		}
	}

	if natRule, ok := d.GetOk("nat_rule"); ok {
		addedNatRules := natRule.([]interface{})
		if len(addedNatRules) > 0 {
			for _, natRuleInterface := range addedNatRules {
				natRule := natRuleInterface.(map[string]interface{})

				req := vins.NATRuleAddRequest{
					VINSID:       vinsId,
					IntIP:        natRule["int_ip"].(string),
					IntPort:      uint(natRule["int_port"].(int)),
					ExtPortStart: uint(natRule["ext_port_start"].(int)),
					ExtPortEnd:   uint(natRule["ext_port_end"].(int)),
					Proto:        natRule["proto"].(string),
				}

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

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

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

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

	// isEnabled := d.Get("enable").(bool)

	hasChangeState := false

	switch vinsData.Status {
	case status.Destroyed:
		d.Set("vins_id", 0)
		d.SetId("")
		return diag.Errorf("The resource cannot be updated because it has been destroyed")
		// return resourceVinsCreate(ctx, d, m)
	case status.Deleted:
		// hasChangeState = true

		// req := vins.RestoreRequest{
		// 	VINSID: vinsData.ID,
		// }

		// _, err := c.CloudAPI().VINS().Restore(ctx, req)
		// if err != nil {
		// 	warnings.Add(err)
		// }
	case status.Modeled:
		return diag.Errorf("ViNS are in status: %s, please, contact support for more information", vinsData.Status)
	case status.Created:
	case status.Enabled:
		// if !isEnabled {
		// 	hasChangeState = true
		// 	req := vins.DisableEnableRequest{
		// 		VINSID: vinsData.ID,
		// 	}

		// 	_, err := c.CloudAPI().VINS().Disable(ctx, req)
		// 	if err != nil {
		// 		warnings.Add(err)
		// 	}
		// }
	case status.Enabling:
	case status.Disabled:
		// if isEnabled {
		// 	hasChangeState = true
		// 	req := vins.DisableEnableRequest{
		// 		VINSID: vinsData.ID,
		// 	}

		// 	_, err := c.CloudAPI().VINS().Enable(ctx, req)
		// 	if err != nil {
		// 		warnings.Add(err)
		// 	}
		// }
	case status.Disabling:
	case status.Deleting:
		return diag.Errorf("ViNS are in progress with status: %s", vinsData.Status)
	}

	if hasChangeState {
		vinsData, err = utilityDataVinsCheckPresence(ctx, d, m)
		if err != nil {
			d.SetId("")
			return diag.FromErr(err)
		}
	}

	flattenVins(d, vinsData)

	return warnings.Get()
}

func isContainsIp(els []interface{}, el interface{}) bool {
	for _, elOld := range els {
		elOldConv := elOld.(map[string]interface{})
		elConv := el.(map[string]interface{})
		if elOldConv["ip_addr"].(string) == elConv["ip_addr"].(string) {
			return true
		}
	}
	return false
}

func isContainsNatRule(els []interface{}, el interface{}) bool {
	for _, elOld := range els {
		elOldConv := elOld.(map[string]interface{})
		elConv := el.(map[string]interface{})
		if elOldConv["int_ip"].(string) == elConv["int_ip"].(string) &&
			elOldConv["int_port"].(int) == elConv["int_port"].(int) &&
			elOldConv["ext_port_start"].(int) == elConv["ext_port_start"].(int) {
			return true
		}
	}
	return false
}

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

	if _, ok := d.GetOk("rg_id"); ok {
		haveRGID, err := existRGID(ctx, d, m)
		if err != nil {
			return diag.FromErr(err)
		}

		if !haveRGID {
			return diag.Errorf("resourceVinsUpdate: can't update ViNS because RGID %d is not allowed or does not exist", d.Get("rg_id").(int))
		}
	}

	if _, ok := d.GetOk("ext_net_id"); ok {
		haveExtNetID, err := existExtNetID(ctx, d, m)
		if err != nil {
			return diag.FromErr(err)
		}

		if !haveExtNetID {
			return diag.Errorf("resourceVinsUpdate: can't update ViNS because ExtNetID %d is not allowed or does not exist", d.Get("ext_net_id").(int))
		}
	}

	if _, ok := d.GetOk("account_id"); ok {
		haveAccountID, err := existAccountID(ctx, d, m)
		if err != nil {
			return diag.FromErr(err)
		}

		if !haveAccountID {
			return diag.Errorf("resourceVinsUpdate: can't update ViNS because AccountID %d is not allowed or does not exist", d.Get("account_id").(int))
		}
	}

	if _, ok := d.GetOk("gid"); ok {
		haveGID, err := existGID(ctx, d, m)
		if err != nil {
			return diag.FromErr(err)
		}

		if !haveGID {
			return diag.Errorf("resourceVinsUpdate: can't update ViNS because GID %d is not allowed or does not exist", d.Get("gid").(int))
		}
	}

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

	isEnabled := d.Get("enable").(bool)

	hasChangeState := false

	switch vinsData.Status {
	case status.Destroyed:
		d.SetId("")
		return diag.Errorf("The resource cannot be updated because it has been destroyed")
		// return resourceVinsCreate(ctx, d, m)
	case status.Deleted:
		if restore, ok := d.GetOk("restore"); ok && restore.(bool) {
			req := vins.RestoreRequest{
				VINSID: vinsData.ID,
			}

			_, err := c.CloudAPI().VINS().Restore(ctx, req)
			if err != nil {
				warnings.Add(err)
			}
			hasChangeState = true
		}
	case status.Modeled:
		return diag.Errorf("ViNS are in status: %s, please, contact support for more information", vinsData.Status)
	case status.Created:
	case status.Enabled:
		if !isEnabled {
			req := vins.DisableEnableRequest{
				VINSID: vinsData.ID,
			}

			_, err := c.CloudAPI().VINS().Disable(ctx, req)
			if err != nil {
				warnings.Add(err)
			}
			hasChangeState = true
		}
	case status.Enabling:
	case status.Disabled:
		if isEnabled {
			req := vins.DisableEnableRequest{
				VINSID: vinsData.ID,
			}

			_, err := c.CloudAPI().VINS().Enable(ctx, req)
			if err != nil {
				warnings.Add(err)
			}
			hasChangeState = true
		}
	case status.Disabling:
	case status.Deleting:
		return diag.Errorf("ViNS are in progress with status: %s", vinsData.Status)
	}

	if hasChangeState {
		vinsData, err = utilityDataVinsCheckPresence(ctx, d, m)
		if err != nil {
			d.SetId("")
			return diag.FromErr(err)
		}
	}

	if d.HasChange("enable") {
		enableOld, enableNew := d.GetChange("enable")
		if enableOld.(bool) && !enableNew.(bool) {
			req := vins.DisableEnableRequest{
				VINSID: vinsData.ID,
			}

			_, err := c.CloudAPI().VINS().Disable(ctx, req)
			if err != nil {
				warnings.Add(err)
			}
		} else if !enableOld.(bool) && enableNew.(bool) {
			req := vins.DisableEnableRequest{
				VINSID: vinsData.ID,
			}

			_, err := c.CloudAPI().VINS().Enable(ctx, req)
			if err != nil {
				warnings.Add(err)
			}
		}
	}
	if d.HasChange("ext_net_id") {
		//extnet v1
		oldExtNetId, newExtNedId := d.GetChange("ext_net_id")
		if oldExtNetId.(int) != newExtNedId.(int) {
			log.Debugf("resourceVinsUpdate: changing ViNS ID %s - ext_net_id %d -> %d", d.Id(), oldExtNetId.(int), newExtNedId.(int))

			if oldExtNetId.(int) > 0 {
				// there was preexisting external net connection - disconnect ViNS
				req := vins.ExtNetDisconnectRequest{VINSID: vinsData.ID}

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

			if newExtNedId.(int) >= 0 {
				// new external network connection requested - connect ViNS
				req := vins.ExtNetConnectRequest{
					VINSID: vinsData.ID,
					NetID:  uint64(newExtNedId.(int)),
					IP:     "",
				}

				extNetIp, ok := d.GetOk("ext_net_ip")
				if ok && extNetIp.(string) != "" {
					req.IP = extNetIp.(string)
				}

				_, err := c.CloudAPI().VINS().ExtNetConnect(ctx, req)
				if err != nil {
					warnings.Add(err)
				}
			}
		}
	}
	if d.HasChange("ip") {
		deletedIps := make([]interface{}, 0)
		addedIps := make([]interface{}, 0)

		oldIpInterface, newIpInterface := d.GetChange("ip")
		oldIpSlice := oldIpInterface.([]interface{})
		newIpSlice := newIpInterface.([]interface{})

		for _, el := range oldIpSlice {
			if !isContainsIp(newIpSlice, el) {
				deletedIps = append(deletedIps, el)
			}
		}

		for _, el := range newIpSlice {
			if !isContainsIp(oldIpSlice, el) {
				addedIps = append(addedIps, el)
			}
		}

		if len(deletedIps) > 0 {
			for _, ipInterfase := range deletedIps {
				ip := ipInterfase.(map[string]interface{})
				req := vins.IPReleaseRequest{VINSID: vinsData.ID}

				if ip["ip_addr"].(string) != "" {
					req.IPAddr = ip["ip_addr"].(string)
				}
				if ip["mac_addr"].(string) != "" {
					req.MAC = ip["mac_addr"].(string)
				}

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

		if len(addedIps) > 0 {
			for _, ipInterfase := range addedIps {
				ip := ipInterfase.(map[string]interface{})
				req := vins.IPReserveRequest{
					VINSID: vinsData.ID,
					Type:   ip["type"].(string),
				}

				if ip["ip_addr"].(string) != "" {
					req.IPAddr = ip["ip_addr"].(string)
				}
				if ip["mac_addr"].(string) != "" {
					req.MAC = ip["mac_addr"].(string)
				}
				if ip["compute_id"].(int) != 0 {
					req.ComputeID = uint64(ip["compute_id"].(int))
				}

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

	if d.HasChange("nat_rule") {
		deletedNatRules := make([]interface{}, 0)
		addedNatRules := make([]interface{}, 0)

		oldNatRulesInterface, newNatRulesInterface := d.GetChange("nat_rule")
		oldNatRulesSlice := oldNatRulesInterface.([]interface{})
		newNatRulesSlice := newNatRulesInterface.([]interface{})

		for _, el := range oldNatRulesSlice {
			if !isContainsNatRule(newNatRulesSlice, el) {
				deletedNatRules = append(deletedNatRules, el)
			}
		}

		for _, el := range newNatRulesSlice {
			if !isContainsNatRule(oldNatRulesSlice, el) {
				addedNatRules = append(addedNatRules, el)
			}
		}

		if len(deletedNatRules) > 0 {
			for _, natRuleInterface := range deletedNatRules {
				natRule := natRuleInterface.(map[string]interface{})
				req := vins.NATRuleDelRequest{
					VINSID: vinsData.ID,
					RuleID: int64(natRule["rule_id"].(int)),
				}

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

		if len(addedNatRules) > 0 {
			for _, natRuleInterface := range addedNatRules {
				natRule := natRuleInterface.(map[string]interface{})
				req := vins.NATRuleAddRequest{
					VINSID:       vinsData.ID,
					IntIP:        natRule["int_ip"].(string),
					IntPort:      uint(natRule["int_port"].(int)),
					ExtPortStart: uint(natRule["ext_port_start"].(int)),
				}

				if natRule["ext_port_end"].(int) != 0 {
					req.ExtPortEnd = uint(natRule["ext_port_end"].(int))
				}
				if natRule["proto"].(string) != "" {
					req.Proto = natRule["proto"].(string)
				}

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

	if d.HasChange("dns") {
		// empty "dns" is allowed, it will update vnfs.dhcp.config.dns from current values to empty list
		dnsInterface := d.Get("dns").(*schema.Set).List()
		dnsList := make([]string, 0, len(dnsInterface))
		for _, item := range dnsInterface {
			dnsList = append(dnsList, item.(string))
		}

		req := vins.DNSApplyRequest{
			VINSID:  vinsData.ID,
			DNSList: dnsList,
		}

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

	if d.HasChange("vnfdev_restart") {
		if oldRestart, newRestart := d.GetChange("vnfdev_restart"); oldRestart == false && newRestart == true {
			req := vins.VNFDevRestartRequest{VINSID: vinsData.ID}

			_, err := c.CloudAPI().VINS().VNFDevRestart(ctx, req)
			if err != nil {
				warnings.Add(err)
			}
		}
	}
	if d.HasChange("vnfdev_redeploy") {
		if oldRedeploy, newRedeploy := d.GetChange("vnfdev_redeploy"); oldRedeploy == false && newRedeploy == true {
			req := vins.VNFDevRedeployRequest{VINSID: vinsData.ID}

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

	if d.HasChange("zone_id") {
		zoneID := uint64(d.Get("zone_id").(int))

		req := vins.MigrateToZoneRequest{
			VINSID: vinsData.ID,
			ZoneID: zoneID,
		}

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

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

func resourceVinsDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	c := m.(*controller.ControllerCfg)
	vinsId, _ := strconv.ParseUint(d.Id(), 10, 64)
	req := vins.DeleteRequest{
		VINSID:      vinsId,
		Force:       d.Get("force").(bool),
		Permanently: d.Get("permanently").(bool),
	}

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

	d.SetId("")

	return nil
}

func extNetSchemaMake() map[string]*schema.Schema {
	return map[string]*schema.Schema{
		"ext_net_id": {
			Type:     schema.TypeInt,
			Default:  -1,
			Optional: true,
		},
		"ext_net_ip": {
			Type:     schema.TypeString,
			Optional: true,
			Default:  "",
		},
	}
}

func ipSchemaMake() map[string]*schema.Schema {
	return map[string]*schema.Schema{
		"type": {
			Type:         schema.TypeString,
			Required:     true,
			ValidateFunc: validation.StringInSlice([]string{"DHCP", "VIP", "EXCLUDED"}, false),
		},
		"ip_addr": {
			Type:     schema.TypeString,
			Optional: true,
		},
		"mac_addr": {
			Type:     schema.TypeString,
			Optional: true,
		},
		"compute_id": {
			Type:     schema.TypeInt,
			Optional: true,
		},
	}
}

func natRuleSchemaMake() map[string]*schema.Schema {
	return map[string]*schema.Schema{
		"int_ip": {
			Type:     schema.TypeString,
			Optional: true,
			Computed: true,
		},
		"int_port": {
			Type:     schema.TypeInt,
			Optional: true,
			Computed: true,
		},
		"ext_port_start": {
			Type:     schema.TypeInt,
			Optional: true,
			Computed: true,
		},
		"ext_port_end": {
			Type:     schema.TypeInt,
			Optional: true,
			Computed: true,
		},
		"proto": {
			Type:         schema.TypeString,
			Optional:     true,
			ValidateFunc: validation.StringInSlice([]string{"tcp", "udp"}, false),
			Computed:     true,
		},
		"rule_id": {
			Type:     schema.TypeInt,
			Computed: true,
		},
	}
}

func resourceVinsSchemaMake() map[string]*schema.Schema {
	rets := dataSourceVinsSchemaMake()
	rets["name"] = &schema.Schema{
		Type:     schema.TypeString,
		Required: true,
	}
	rets["rg_id"] = &schema.Schema{
		Type:     schema.TypeInt,
		Computed: true,
		Optional: true,
	}
	rets["account_id"] = &schema.Schema{
		Type:     schema.TypeInt,
		Optional: true,
		Computed: true,
	}
	rets["ext_net_id"] = &schema.Schema{
		Type:     schema.TypeInt,
		Optional: true,
		Default:  -1,
	}
	rets["ext_ip_addr"] = &schema.Schema{
		Type:     schema.TypeString,
		Optional: true,
		Default:  "",
	}
	rets["ipcidr"] = &schema.Schema{
		Type:     schema.TypeString,
		Optional: true,
	}
	rets["pre_reservations_num"] = &schema.Schema{
		Type:     schema.TypeInt,
		Optional: true,
	}
	rets["gid"] = &schema.Schema{
		Type:     schema.TypeInt,
		Optional: true,
		Computed: true,
	}
	rets["enable"] = &schema.Schema{
		Type:     schema.TypeBool,
		Optional: true,
		Default:  true,
	}
	rets["permanently"] = &schema.Schema{
		Type:     schema.TypeBool,
		Optional: true,
		Default:  false,
	}
	rets["force"] = &schema.Schema{
		Type:     schema.TypeBool,
		Optional: true,
		Default:  false,
	}
	rets["ext_net"] = &schema.Schema{
		Type:     schema.TypeList,
		Optional: true,
		MaxItems: 1,
		Elem: &schema.Resource{
			Schema: extNetSchemaMake(),
		},
	}
	rets["ip"] = &schema.Schema{
		Type:     schema.TypeList,
		Optional: true,
		Elem: &schema.Resource{
			Schema: ipSchemaMake(),
		},
	}
	rets["nat_rule"] = &schema.Schema{
		Type:     schema.TypeList,
		Optional: true,
		Elem: &schema.Resource{
			Schema: natRuleSchemaMake(),
		},
	}
	rets["desc"] = &schema.Schema{
		Type:        schema.TypeString,
		Optional:    true,
		Default:     "",
		Description: "Optional user-defined text description of this ViNS.",
	}
	rets["restore"] = &schema.Schema{
		Type:     schema.TypeBool,
		Optional: true,
		Default:  false,
	}
	rets["vnfdev_restart"] = &schema.Schema{
		Type:     schema.TypeBool,
		Optional: true,
		Default:  false,
	}
	rets["vnfdev_redeploy"] = &schema.Schema{
		Type:     schema.TypeBool,
		Optional: true,
		Default:  false,
	}
	rets["dns"] = &schema.Schema{
		Type:     schema.TypeSet,
		Optional: true,
		Elem: &schema.Schema{
			Type: schema.TypeString,
		},
	}
	rets["vins_id"] = &schema.Schema{
		Type:        schema.TypeInt,
		Computed:    true,
		Description: "Unique ID of the ViNS. If ViNS ID is specified, then ViNS name, rg_id and account_id are ignored.",
	}
	rets["zone_id"] = &schema.Schema{
		Type:        schema.TypeInt,
		Optional:    true,
		Computed:    true,
		Description: "ID of the Zone to put ViNS into",
	}
	rets["enable_secgroups"] = &schema.Schema{
		Type:        schema.TypeBool,
		Optional:    true,
		Default:     false,
		Description: "enable security groups",
	}

	return rets
}

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

		CreateContext: resourceVinsCreate,
		ReadContext:   resourceVinsRead,
		UpdateContext: resourceVinsUpdate,
		DeleteContext: resourceVinsDelete,

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