package containers

import (
	"encoding/json"
	"floares/config"
	"github.com/samber/lo"
	"log"
	"net/http"
	"strings"
	"time"
)

type Ports struct {
	PrivatePort int `json:"container_port"`
	PublicPort  int `json:"host_port"`
}
type Port struct {
	PrivatePort int    `json:"PrivatePort"`
	PublicPort  int    `json:"PublicPort"`
	Type        string `json:"Type"`
}
type ListContainers struct {
	Id      string   `json:"id"`
	Name    string   `json:"name"`
	Image   string   `json:"image"`
	Created string   `json:"created"`
	Ports   []Ports  `json:"ports"`
	Network []string `json:"network"`
	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   []Port   `json:"Ports"`
	Network struct {
		Networks map[string]any `json:"Networks"`
	} `json:"NetworkSettings"`
	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)
	}
	list := make([]ListContainers, 0)
	for _, container := range containers {
		var p []Ports
		for _, containerPort := range container.Ports {
			p = append(p, Ports{
				PrivatePort: containerPort.PrivatePort,
				PublicPort:  containerPort.PublicPort,
			})
		}
		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,
			Network: lo.Keys(container.Network.Networks),
			Ports:   append([]Ports{}, p...),
		})
	}

	return list
}
