package api

import (
	"context"
	"io"
	"strings"
)

type Query interface {
	List(ctx context.Context, param *ListParam) (*ListData, error)
	Download(ctx context.Context, param *DownloadParam) (*DownloadData, error)
}

type ListParam struct {
	Provider     string
	Region       string
	OrgID        string
	ProjectID    string
	ClusterID    string
	Instances    string
	StartUnixSec int64
	EndUnixSec   int64
}

// InRange check if ts is in [param.StartUnixSec, param.EndUnixSec]
func (param *ListParam) InRange(ts int64) bool {
	if ts >= param.StartUnixSec && ts <= param.EndUnixSec {
		return true
	}
	return false
}

func (param *ListParam) MatchInstance(instance string) bool {
	if param.Instances == "" {
		return true
	}
	return strings.Contains(param.Instances, instance)
}

type DownloadParam struct {
	Provider string
	Region   string
	Key      string
}

type FileMetaInfo struct {
	Filename         string `json:"filename"`
	Key              string `json:"key"`
	DownloadURL      string `json:"download_url"`
	DownloadPath     string `json:"download_path"`
	Size             int64  `json:"size"`
	CreatedAtUnixSec int64  `json:"created_at_unix_sec"`
}

type ListFileRecord struct {
	Instance string         `json:"instance"`
	Files    []FileMetaInfo `json:"files"`
}

type ListData struct {
	Records []ListFileRecord `json:"records"`
}

type DownloadData struct {
	ContentType   string
	ContentLength int64
	Reader        io.ReadCloser
	Headers       map[string]string
}

func (data *DownloadData) Close() error {
	return data.Reader.Close()
}

type HeapResult struct {
	TotalInuseSpace string        `json:"total_inuse_space"`
	TopInuseSpace   []HeapProfile `json:"top_inuse_space"`
}

type HeapProfile struct {
	Flat     string  `json:"flat"`
	FlatPerc float64 `json:"flat_perc"`
	SumPerc  float64 `json:"sum_perc"`
	Cum      string  `json:"cum"`
	CumPerc  float64 `json:"cum_perc"`
	Function string  `json:"function"`
}
