package image

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

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

// ListRequest struct to get list of available images
type ListRequest struct {
	// Filter images by storage endpoint provider ID
	// Required: false
	SepID uint64 `url:"sepId,omitempty" json:"sepId,omitempty"`

	// Find by ID
	// Required: false
	ByID uint64 `url:"by_id,omitempty" json:"by_id,omitempty"`

	// Find by name
	// Required: false
	Name string `url:"name,omitempty" json:"name,omitempty"`

	// Find by status
	// Required: false
	Status string `url:"status,omitempty" json:"status,omitempty"`

	// Find by type
	// Required: false
	TypeImage string `url:"typeImage,omitempty" json:"typeImage,omitempty"`

	// Find by image size
	// Required: false
	ImageSize uint64 `url:"imageSize,omitempty" json:"imageSize,omitempty"`

	// Find by SEP name
	// Required: false
	SEPName string `url:"sepName,omitempty" json:"sepName,omitempty"`

	// Find by pool
	// Required: false
	Pool string `url:"pool,omitempty" json:"pool,omitempty"`

	// Find by public True or False
	// Required: false
	Public interface{} `url:"public,omitempty" json:"public,omitempty" validate:"omitempty,isBool"`

	// Find by hot resize True or False
	// Required: false
	HotResize interface{} `url:"hotResize,omitempty" json:"hotResize,omitempty" validate:"omitempty,isBool"`

	// Find by bootable True or False
	// Required: false
	Bootable interface{} `url:"bootable,omitempty" json:"bootable,omitempty" validate:"omitempty,isBool"`

	// Sort by one of supported fields, format +|-(field)
	// Required: false
	SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`

	// Page number
	// Required: false
	Page uint64 `url:"page,omitempty" json:"page,omitempty"`

	// Page size
	// Required: false
	Size uint64 `url:"size,omitempty" json:"size,omitempty"`

	// Find by enabled True or False
	// Required: false
	Enabled interface{} `url:"enabled,omitempty" json:"enabled,omitempty" validate:"omitempty,isBool"`

	// Find by storage policy id
	// Required: false
	StoragePolicyID uint64 `url:"storage_policy_id,omitempty" json:"storage_policy_id,omitempty"`
}

// List gets list of information about images as a ListImages struct
func (i Image) List(ctx context.Context, req ListRequest) (*ListImages, error) {

	res, err := i.ListRaw(ctx, req)
	if err != nil {
		return nil, err
	}

	list := ListImages{}

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

	return &list, nil
}

// ListRaw gets list of information about images as an array of bytes
func (i Image) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {

	if err := validators.ValidateRequest(req); err != nil {
		return nil, validators.ValidationErrors(validators.GetErrors(err))
	}

	url := "/cloudbroker/image/list"

	res, err := i.client.DecortApiCall(ctx, http.MethodPost, url, req)
	return res, err
}
