package containers

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

type Create struct {
	Image   string `json:"image,required"`
	Name    string `json:"name,omitempty"`
	Network string `json:"network,required"`
	Port    string `json:"port,omitempty"`
	Start   bool   `json:"start,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"`
	Name  string `json:"name"`
	Netns struct {
		Mode string `json:"nsmode"`
	} `json:"netns"`
	Port     []PortMapping          `json:"portmappings"`
	Networks map[string]NetSettings `json:"networks"`
}
type NetSettings struct {
	Aliases       []string `json:"aliases,omitempty"`
	InterfaceName string   `json:"interface_name"`
}
type PortMapping struct {
	HostPort      int `json:"host_port"`
	ContainerPort int `json:"container_port"`
}

func (c *Create) Create() (string, error) {
	var container create
	container.Image = c.Image
	container.Name = c.Name
	var port []PortMapping
	for _, v := range strings.Split(c.Port, ",") {
		p := strings.Split(v, ":")
		if len(p) != 2 {
			continue
		}
		port1, _ := strconv.Atoi(p[0])
		port2, _ := strconv.Atoi(p[1])
		port = append(port, PortMapping{
			HostPort:      port1,
			ContainerPort: port2,
		})
	}
	container.Networks = make(map[string]NetSettings)
	container.Networks["podman"] = NetSettings{
		InterfaceName: "ens0",
	}
	for k, v := range strings.Split(c.Network, ",") {
		log.Println(v)
		container.Networks[v] = NetSettings{
			InterfaceName: "ens" + strconv.Itoa(k),
		}
	}
	container.Port = port
	container.Netns = struct {
		Mode string `json:"nsmode"`
	}{Mode: "bridge"}
	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()

	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)
	Start(createJson.Id)
	return createJson.Id, nil
}
