package pods

import (
	"log"

	"github.com/containers/podman/v4/pkg/bindings/containers"
	"github.com/containers/podman/v4/pkg/specgen"
	runtime_spec "github.com/opencontainers/runtime-spec/specs-go"
	"github.com/spf13/viper"
)

func CreateContainer() (string, error) {
	image := viper.GetString("image")
	conn := Socket
	envmap := make(map[string]string)
	driDevice := runtime_spec.LinuxDevice{
		Path: viper.GetString("dri_node"),
	}
	for envvar, value := range viper.GetStringMap("envvars") {
		envmap[envvar] = value.(string)
	}
	s := specgen.NewSpecGenerator(image, false)
	s.Env = envmap

	// Experimental DRI support for GPU acceleration in Container
	if viper.GetBool("dri") == true {
		s.Devices = []runtime_spec.LinuxDevice{driDevice}
	}
	createResponse, err := containers.CreateWithSpec(conn, s, nil)
	log.Println("Created Container ", createResponse.ID, err, createResponse.Warnings)

	return createResponse.ID, err
}

func StartContainer(id string) error {
	return containers.Start(Socket, id, nil)
}

func DestroyContainer(id string) error {
	conn := Socket
	log.Println("Deleting Container", id)
	if err := containers.Kill(conn, id, nil); err != nil {
		log.Println(err)
		return err
	}
	if _, err := containers.Remove(conn, id, nil); err != nil {
		log.Println(err)
		return err
	}
	return nil
}

func GetContainerIP(id string) (string, error) {
	conn := Socket

	container, err := containers.Inspect(conn, id, nil)
	if err != nil {
		log.Println("Could not get IP of container", err)
		return "", err
	}
	ip := container.NetworkSettings.IPAddress

	return ip, err
}
