package images

import (
	"encoding/json"
	"floares/config"
	"floares/lib/model"
	"net/http"
	"strconv"
	"time"
)

type Image struct {
	Id        string `json:"id"`
	Name      string `json:"name"`
	Tag       string `json:"tag"`
	Digest    string `json:"digest"`
	CreatedAt string `json:"created_at"`
	Size      string `json:"size"`
}

func List() []Image {
	var images []model.Image

	req, _ := http.NewRequest(http.MethodGet, config.Entrypoint+"/images/json", nil)
	resp, _ := http.DefaultClient.Do(req)
	defer resp.Body.Close()
	json.NewDecoder(resp.Body).Decode(&images)
	var imagesList []Image
	for _, v := range images {
		imagesList = append(imagesList, Image{
			Id:        v.Id[7:],
			Name:      v.Names[0],
			Tag:       v.RepoTags[0],
			Digest:    v.Digest,
			CreatedAt: time.Unix(int64(v.Created), 0).Format(time.DateTime),
			Size:      strconv.Itoa(v.Size/1024/1024) + " MB",
		})
	}
	return imagesList
}
