package kvmx86

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

	"repository.basistech.ru/BASIS/decort-golang-sdk/internal/constants"
	"repository.basistech.ru/BASIS/decort-golang-sdk/internal/validators"
)

type Interface struct {
	// Network type
	// Should be one of:
	//	- VINS
	//	- EXTNET
	//  - VFNIC
	//  - DPDK
	//  - EMPTY
	//  - SDN
	//  - TRUNK
	NetType string `url:"netType" json:"netType" validate:"required,kvmx86NetType"`

	// Network ID for connect
	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"`

	// Net mask
	// Used only to DPDK or VFNIC net type
	// Required: false
	NetMask uint64 `url:"netMask,omitempty" json:"netMask,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"`

	// Flag indicating whether default gateway are enabled for this interface, not applicable to netType EXTNET, VFNIC, TRUNK, or SDN
	// Default: true
	// Required: false
	EnableDefaultGateway interface{} `url:"enable_default_gateway,omitempty" json:"enable_default_gateway,omitempty" validate:"omitempty,isBool"`

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

	// SDN Object Group IDs
	// Required: false
	SDNObjectGroupIDs []string `url:"sdn_object_group_ids,omitempty" json:"sdn_object_group_ids,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"`

	// List of QoS Policy IDs to apply to this interface (default: []), Allow used only with netType VINS, EXTNET and DPDK
	// Required: false
	QoSPolicies []uint64 `url:"qos_policies,omitempty" json:"qos_policies,omitempty"`
}

// DataDisk detailed struct for DataDisks field in CreateRequest, CreateBlankRequest and MassCreateRequest
type DataDisk struct {
	// Name for disk
	// Required: true
	DiskName string `url:"diskName" json:"diskName" validate:"required"`

	// Disk size in GB
	// Required: true
	Size uint64 `url:"size" json:"size" validate:"required"`

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

	// Storage endpoint provider ID
	// By default the same with boot disk
	// Required: false
	SepID uint64 `url:"sepId,omitempty" json:"sepId,omitempty"`

	// Pool name
	// By default will be chosen automatically
	// Required: false
	Pool string `url:"pool,omitempty" json:"pool,omitempty"`

	// Optional description
	// Required: false
	Description string `url:"desc,omitempty" json:"desc,omitempty"`

	// Specify image id for create disk from template
	// Required: false
	ImageID uint64 `url:"imageId,omitempty" json:"imageId,omitempty"`

	// Cache mode for disk
	// Required: false
	Cache string `url:"cache,omitempty" json:"cache,omitempty"`

	// Discard
	// Required: false
	Discard string `url:"discard,omitempty" json:"discard,omitempty"`

	// Attach disk in read-only mode
	// Required: false
	// Default: false
	ReadOnly bool `url:"read_only,omitempty" json:"read_only,omitempty"`
}

// CreateRequest struct to create KVM x86 VM
type CreateRequest 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 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"`

	// The OS version that will be installed on the virtual machine
	// Required: false
	OSVersion string `url:"os_version,omitempty" json:"os_version,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 []Interface `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 VM upon success
	// Required: false
	Start bool `url:"start" json:"start"`

	// Node ID
	// Required: false
	NodeID uint64 `url:"node_id,omitempty" json:"node_id,omitempty"`

	// Custom fields for Compute. Must be dict
	// Required: false
	CustomField string `url:"customFields,omitempty" json:"customFields,omitempty"`

	// Rule for VM placement with NUMA affinity.
	// Possible values - none (placement without NUMA affinity),
	// strict (strictly with NUMA affinity, if not possible - do not start VM),
	// loose (use NUMA affinity if possible)
	// Required: false
	// Default: none
	NumaAffinity string `url:"numa_affinity,omitempty" json:"numa_affinity,omitempty" validate:"omitempty,numaAffinity"`

	// Run VM on dedicated CPUs. To use this feature, the system must be pre-configured by allocating CPUs on the physical node
	// Required: false
	// Default: false
	CPUPin bool `url:"cpu_pin" json:"cpu_pin"`

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

	// Use Huge Pages to allocate RAM of the virtual machine. The system must be pre-configured by allocating Huge Pages on the physical node
	// Required: false
	// Default: false
	HPBacked bool `url:"hp_backed" json:"hp_backed"`

	// Recommended isolated CPUs. Field is ignored if compute.cpupin=False or compute.pinned=False
	// Required: false
	PreferredCPU []int64 `url:"preferredCpu,omitempty" json:"preferredCpu,omitempty" validate:"omitempty,preferredCPU"`

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

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

	// Boot Disk Discard
	// Required: false
	BootDiskDiscard string `url:"boot_disk_discard,omitempty" json:"boot_disk_discard,omitempty"`

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

	// CPU alignment profile name
	// Required: false
	CPUAlignmentProfile string `url:"cpu_alignment_profile,omitempty" json:"cpu_alignment_profile,omitempty"`

	// Clock type for the VM
	// Required: false
	// Default: default
	Clock string `url:"clock,omitempty" json:"clock,omitempty"`

	// Watchdog action
	// Required: false
	// Default: reset
	WatchdogAction string `url:"watchdog_action,omitempty" json:"watchdog_action,omitempty" validate:"omitempty,watchdogAction"`

	// Memory balloon mode. One of ["auto","legacy","none"]
	// Required: false
	// Default: "auto"
	MemoryBalloonMode string `url:"memory_balloon_mode,omitempty" json:"memory_balloon_mode,omitempty" validate:"omitempty,memoryBalloonMode"`
}

// GetRAM returns RAM field values
func (r CreateRequest) GetRAM() map[string]uint64 {
	res := make(map[string]uint64, 1)

	res["RAM"] = r.RAM

	return res
}

type wrapperCreateRequest struct {
	CreateRequest
	AsyncMode bool `json:"asyncMode"`
}

// Create creates KVM PowerPC VM based on specified OS image
func (k KVMX86) Create(ctx context.Context, req CreateRequest) (uint64, error) {
	err := validators.ValidateRequest(req)
	if err != nil {
		return 0, validators.ValidationErrors(validators.GetErrors(err))
	}

	url := "/cloudbroker/kvmx86/create"

	res, err := k.client.DecortApiCallCtype(ctx, http.MethodPost, url, constants.MIMEJSON, wrapperCreateRequest{
		CreateRequest: req,
		AsyncMode:     false,
	})
	if err != nil {
		return 0, err
	}

	return strconv.ParseUint(string(res), 10, 64)
}

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

	url := "/cloudbroker/kvmx86/create"

	res, err := k.client.DecortApiCallCtype(ctx, http.MethodPost, url, constants.MIMEJSON, wrapperCreateRequest{
		CreateRequest: req,
		AsyncMode:     true,
	})
	if err != nil {
		return "", err
	}

	var taskID string

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

	return taskID, nil
}
