package images

import (
	"context"
	"encoding/json"
	"floares/config"
	"fmt"
	"io"
	"log"
	"net/http"
)

type PullRsp struct {
	Images []string `json:"images"`
	Id     string   `json:"id"`
	Error  string   `json:"errr,omitempty"`
	Info   string   `json:"info,omitempty"`
}

func Pull(ref string) PullRsp {
	var pull PullRsp
	req, _ := http.NewRequestWithContext(context.Background(), http.MethodPost, config.Entrypoint+fmt.Sprintf("/v2.2.2/libpod/images/pull?reference=%s&quiet=true", ref), nil)
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return PullRsp{
			Error: err.Error(),
		}
	}
	defer func(Body io.ReadCloser) {
		err = Body.Close()
		if err != nil {
			log.Printf("Failed to close response body: %v", err)
		}
	}(resp.Body)
	if resp.StatusCode != http.StatusOK {
		return PullRsp{
			Error: "status code " + resp.Status,
		}
	}
	_ = json.NewDecoder(resp.Body).Decode(&pull)

	return pull

}
