package containers

import (
	"encoding/json"
	"floares/config"
	"log"
	"net/http"
	"strings"
	"time"
)

type ListContainers struct {
	Id      string        `json:"id"`
	Name    string        `json:"name"`
	Image   string        `json:"image"`
	Created string        `json:"created"`
	Ports   []interface{} `json:"ports"`
	State   string        `json:"state"`
}
type Containers struct {
	Id      string   `json:"Id"`
	Names   []string `json:"Names"`
	Image   string   `json:"Image"`
	ImageID string   `json:"ImageID"`
	Command string   `json:"Command"`
	Created int      `json:"Created"`
	//Ports   []interface{} `json:"Ports"`
	State  string `json:"State"`
	Status string `json:"Status"`
}

func List() []ListContainers {
	var containers []Containers
	req, err := http.NewRequest(http.MethodGet, config.Entrypoint+"/containers/json?all=true", nil)
	if err != nil {
		log.Println("request for containers list error:", err)
		return []ListContainers{}
	}
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Println("request for containers list error:", err)
		return []ListContainers{}
	}
	err = json.NewDecoder(res.Body).Decode(&containers)
	if err != nil {
		log.Println("json decode container list error:", err)
	}
	var list []ListContainers
	for _, container := range containers {
		list = append(list, ListContainers{
			Id:      container.Id,
			Name:    strings.TrimPrefix(container.Names[0], "/"),
			Image:   container.Image,
			Created: time.Unix(int64(container.Created), 0).Format(time.DateTime),
			State:   container.State,
		})
	}
	return list
}
