package containers

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

type Create struct {
	Image string `json:"image,required"`
	Name  string `json:"name,omitempty"`
}
type CreateJson struct {
	Cause    string   `json:"cause"`
	Message  string   `json:"message"`
	Response int      `json:"response"`
	Id       string   `json:"Id,omitempty"`
	Warning  []string `json:"Warnings,omitempty"`
}

type create struct {
	Image string `json:"image"`
}

func (c *Create) Create() (string, error) {
	var container create
	container.Image = c.Image

	str, err := json.Marshal(container)
	if err != nil {
		log.Println(err)
		return "", err
	}
	log.Println(string(str))
	req, _ := http.NewRequest(http.MethodPost, config.Entrypoint+"/v2.1.2/libpod/containers/create", bytes.NewBuffer(str))
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Println(err)
		return "", err
	}
	defer resp.Body.Close()

	b, err := io.ReadAll(resp.Body)
	log.Println(string(b))
	var createJson CreateJson
	err = json.NewDecoder(resp.Body).Decode(&createJson)
	if err != nil {
		log.Println(createJson)
		log.Println(err)
		return "", err
	}
	log.Println(createJson)
	startContainer(createJson.Id)
	return createJson.Id, nil
}
func startContainer(id string) error {
	post, err := http.Post(fmt.Sprintf("/%s/libpod/containers/%s/start", config.Entrypoint, id), "application/json", nil)
	if err != nil {
		return err
	}
	bytes, err := io.ReadAll(post.Body)
	log.Println(string(bytes))
	return err
}
