package pods

import (
	"context"
	"log"
	"time"

	"github.com/containers/podman/v4/pkg/bindings"
	"github.com/containers/podman/v4/pkg/bindings/containers"
	"github.com/containers/podman/v4/pkg/bindings/images"
	"github.com/containers/podman/v4/pkg/domain/entities"
	"github.com/spf13/viper"
)

var Socket context.Context

var OldContainers []string

func socketConnection() context.Context {
	uri := "unix:///run/podman/podman.sock"
	conn, err := bindings.NewConnection(context.Background(), uri)
	if err != nil {
		log.Fatal(err)
	}
	return conn
}

func ConnectSocket() {
	Socket = socketConnection()
}

func PullImage() error {
	for {
		log.Println("Downloading Container image ", viper.GetString("image"))
		image := viper.GetString("image")
		conn := Socket
		_, err := images.Pull(conn, image, nil)
		if err != nil {
			log.Println(err)
			return err
		}

		time.Sleep(1 * time.Hour)
	}

}

// Cleanup deletes Containers older than the specified maximum Age (Equal to session cookie maximum age)
func Cleanup() error {
	log.Println("Starting cleanup function")
	containerList := containerList()

	for _, container := range containerList {
		for _, ctid := range OldContainers {
			if container.ID == ctid {
				err := containers.Kill(Socket, container.ID, nil)
				if err != nil {
					log.Println(err)
					return err
				}
				_, err = containers.Remove(Socket, container.ID, nil)
				if err != nil {
					log.Println(err)
					return err
				}
			}
		}

	}
	return nil
}

func containerList() []entities.ListContainer {
	containerList, err := containers.List(Socket, nil)
	if err != nil {
		log.Println("Could not get Containers", err)
	}
	return containerList
}
