package kvmx86

import (
	"context"
	"encoding/json"
	"net/http"

	"repository.basistech.ru/BASIS/dynamix-golang-sdk/v14/internal/validators"
)

type InterfaceMassCreate struct {
	// Network type
	// Should be one of:
	//	- VINS
	//	- EXTNET
	//  - TRUNK
	//  - SDN
	// For SDN, one of the fields sdn_interface_id or sdn_segment_id is specified, but not both at the same time
	// Required: false
	NetType string `url:"netType" json:"netType" validate:"required,massCreateNetType"`

	// Network ID for connect
	// Required: false
	NetID uint64 `url:"netId" json:"netId" validate:"required"`

	// IP address to assign to this VM when connecting to the specified network
	// Required: false
	IPAddr string `url:"ipAddr,omitempty" json:"ipAddr,omitempty"`

	// Used for EXTNET, TRUNK and DPDK
	// Must be 1500-9216
	// Required: false
	MTU uint64 `url:"mtu,omitempty" json:"mtu,omitempty" validate:"omitempty,mtu"`

	// MAC address to assign to this VM when connecting to the specified network
	// Required: false
	MAC string `url:"mac,omitempty" json:"mac,omitempty" validate:"omitempty"`

	// SDN interface id
	// Required: false
	SDNInterfaceID string `url:"sdn_interface_id,omitempty" json:"sdn_interface_id,omitempty"`

	// List of security group IDs to assign to this interface
	// Required: false
	SecGroups []uint64 `url:"security_groups,omitempty" json:"security_groups,omitempty"`

	// Flag indicating whether security groups are enabled for this interface
	// Not applicable to netType VFNIC, TRUNK, or SDN
	// Required: false
	EnableSecGroups bool `url:"enable_secgroups,omitempty" json:"enable_secgroups,omitempty"`

	// Flag indicating whether this interface is enabled (only for VINS, EXTNET, DPDK, SDN, TRUNK)
	// Required: false
	Enabled interface{} `url:"enabled,omitempty" json:"enabled,omitempty" validate:"omitempty,isBool"`

	// SDN Segment ID
	// Required: false
	SDNSegmentID string `url:"sdn_segment_id,omitempty" json:"sdn_segment_id,omitempty"`

	// SDN Object Group ID
	// Required: false
	SDNObjectGroupID string `url:"sdn_object_group_id,omitempty" json:"sdn_object_group_id,omitempty"`

	// SDN Logical Port Display Name
	// Required: false
	SDNLogicalPortDisplayName string `url:"sdn_logical_port_display_name,omitempty" json:"sdn_logical_port_display_name,omitempty"`

	// SDN Logical Port Description
	// Required: false
	SDNLogicalPortDescription string `url:"sdn_logical_port_description,omitempty" json:"sdn_logical_port_description,omitempty"`
}

// MassCreateRequest struct to mass create KVM x86
type MassCreateRequest struct {
	// ID of the resource group, which will own this VM
	// Required: true
	RGID uint64 `url:"rgId" json:"rgId" validate:"required"`

	// Name of this VM.
	// Must be unique among all VMs (including those in DELETED state) in target resource group
	// Required: true
	Name string `url:"name" json:"name" validate:"required"`

	// Number of VMs
	// Required: true
	Count uint64 `url:"count" json:"count" validate:"required"`

	// Number CPUs to allocate to this VM
	// Required: true
	CPU uint64 `url:"cpu" json:"cpu" validate:"required"`

	// Volume of RAM in MB to allocate to this VM
	// Required: true
	RAM uint64 `url:"ram" json:"ram" validate:"required"`

	// Storage policy id of сompute. The rules of the specified storage policy will be used.
	// Required: true
	StoragePolicyID uint64 `url:"storage_policy_id" json:"storage_policy_id" validate:"required"`

	// If True, the imageId, bootDisk, sepId, pool parameters are ignored and the compute is created without a boot disk in the stopped state
	// Required: false
	WithoutBootDisk bool `url:"withoutBootDisk" json:"withoutBootDisk"`

	// ID of the OS image to base this VM on; Could be boot disk image or CD-ROM image
	// Required: false
	ImageID uint64 `url:"imageId,omitempty" json:"imageId,omitempty"`

	// Size of the boot disk in GB
	// Required: false
	BootDisk uint64 `url:"bootDisk,omitempty" json:"bootDisk,omitempty"`

	// ID of SEP to create boot disk on.
	// Uses images SEP ID if not set
	// Required: false
	SEPID uint64 `url:"sepId,omitempty" json:"sepId,omitempty"`

	// Pool to use if SEP ID is set, can be also empty if needed to be chosen by system
	// Required: false
	Pool string `url:"pool,omitempty" json:"pool,omitempty"`

	// Slice of structs with data disk description. Each disk has parameters: required - diskName, size; optional - sepId, pool, desc and imageId.
	// If not specified, compute will be created without disks.
	// To create compute without disks, pass initialized empty slice .
	// Required: false
	DataDisks []DataDisk `url:"-" json:"dataDisks,omitempty" validate:"omitempty,dive"`

	// Slice of structs with net interface description.
	// If not specified, compute will be created with default interface from RG.
	// To create compute without interfaces, pass initialized empty slice .
	// Required: false
	Interfaces []InterfaceMassCreate `url:"-" json:"interfaces,omitempty" validate:"omitempty,dive"`

	// Input data for cloud-init facility
	// Required: false
	UserData string `url:"userdata,omitempty" json:"userdata,omitempty"`

	// Text description of this VM
	// Required: false
	Description string `url:"desc,omitempty" json:"desc,omitempty"`

	// Start after create of not
	// Required: false
	Start bool `url:"start" json:"start"`

	// Type of the emulated system, Q35 or i440fx
	// Required: false
	Chipset string `url:"chipset,omitempty" json:"chipset,omitempty" validate:"omitempty,chipset"`

	// Zone ID
	// Required: false
	ZoneID uint64 `url:"zoneId,omitempty" json:"zoneId,omitempty"`

	// The OS version that will be installed on the virtual machine
	// Required: false
	OSVersion string `url:"os_version,omitempty" json:"os_version,omitempty"`

	// Cache mode for boot disk
	// Required: false
	BootDiskCache string `url:"boot_disk_cache,omitempty" json:"boot_disk_cache,omitempty"`

	// Boot Disk BLK Discard
	// Required: false
	BootDiskBLKDiscard interface{} `url:"boot_disk_blkdiscard" json:"boot_disk_blkdiscard" validate:"omitempty,isBool"`

	// Priority weight of the VM: higher value means higher priority and later migration
	// Required: false
	// Default: 1
	Weight uint64 `url:"weight,omitempty" json:"weight,omitempty"`
}

type asyncWrapperMassCreateRequest struct {
	wrapperMassCreateRequest
	AsyncMode bool `url:"asyncMode"`
}

// GetRAM returns RAM field values
func (r MassCreateRequest) GetRAM() map[string]uint64 {

	res := make(map[string]uint64, 1)

	res["RAM"] = r.RAM

	return res
}

type wrapperMassCreateRequest struct {
	MassCreateRequest
	Interfaces []string `url:"interfaces,omitempty"`
	DataDisks  []string `url:"dataDisks,omitempty"`
}

// MassCreate creates KVM x86 computes based on specified OS image
func (k KVMX86) MassCreate(ctx context.Context, req MassCreateRequest) ([]uint64, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return nil, validators.ValidationErrors(validators.GetErrors(err))
	}

	var interfaces []string

	if req.Interfaces != nil && len(req.Interfaces) != 0 {
		interfaces = make([]string, 0, len(req.Interfaces))

		for i := range req.Interfaces {
			b, err := json.Marshal(req.Interfaces[i])
			if err != nil {
				return nil, err
			}

			interfaces = append(interfaces, string(b))
		}
	} else if req.Interfaces != nil && len(req.Interfaces) == 0 {
		interfaces = []string{"[]"}
	}

	var dataDisks []string

	if req.DataDisks != nil && len(req.DataDisks) != 0 {
		dataDisks = make([]string, 0, len(req.DataDisks))

		for i := range req.DataDisks {
			b, err := json.Marshal(req.DataDisks[i])
			if err != nil {
				return nil, err
			}

			dataDisks = append(dataDisks, string(b))
		}
	}

	reqWrapped := wrapperMassCreateRequest{
		MassCreateRequest: req,
		Interfaces:        interfaces,
		DataDisks:         dataDisks,
	}

	finalReq := asyncWrapperMassCreateRequest{wrapperMassCreateRequest: reqWrapped, AsyncMode: false}

	url := "/cloudbroker/kvmx86/massCreate"

	res, err := k.client.DecortApiCall(ctx, http.MethodPost, url, finalReq)
	if err != nil {
		return nil, err
	}

	computes := make([]uint64, 0)

	err = json.Unmarshal(res, &computes)
	if err != nil {
		return nil, err
	}

	return computes, nil
}

// MassCreate creates KVM x86 computes based on specified OS image in async mode
func (k KVMX86) MassCreateAsync(ctx context.Context, req MassCreateRequest) (string, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return "", validators.ValidationErrors(validators.GetErrors(err))
	}

	var interfaces []string

	if req.Interfaces != nil && len(req.Interfaces) != 0 {
		interfaces = make([]string, 0, len(req.Interfaces))

		for i := range req.Interfaces {
			b, err := json.Marshal(req.Interfaces[i])
			if err != nil {
				return "", err
			}

			interfaces = append(interfaces, string(b))
		}
	} else if req.Interfaces != nil && len(req.Interfaces) == 0 {
		interfaces = []string{"[]"}
	}

	var dataDisks []string

	if req.DataDisks != nil && len(req.DataDisks) != 0 {
		dataDisks = make([]string, 0, len(req.DataDisks))

		for i := range req.DataDisks {
			b, err := json.Marshal(req.DataDisks[i])
			if err != nil {
				return "", err
			}

			dataDisks = append(dataDisks, string(b))
		}
	}

	reqWrapped := wrapperMassCreateRequest{
		MassCreateRequest: req,
		Interfaces:        interfaces,
		DataDisks:         dataDisks,
	}

	finalReq := asyncWrapperMassCreateRequest{wrapperMassCreateRequest: reqWrapped, AsyncMode: true}

	url := "/cloudbroker/kvmx86/massCreate"

	res, err := k.client.DecortApiCall(ctx, http.MethodPost, url, finalReq)
	if err != nil {
		return "", err
	}

	var computes string

	err = json.Unmarshal(res, &computes)
	if err != nil {
		return "", err
	}

	return computes, nil
}
