package docker

import (
	"errors"
	"strings"

	S "bitbucket.org/robert2206/automation/modules/settings"
	docker "github.com/fsouza/go-dockerclient"
)

type ContainerDescriptor struct {
	Name      *string
	ImageName *string
}

func Create(dsc *ContainerDescriptor) {

}

func Remove() {

}

// Start container
func Start(idOrName string) error {
	cli, err := getClientFor(idOrName)

	if err != nil {
		return err
	}

	return cli.StartContainer(idOrName, nil)
}

// Restart container
func Restart(idOrName string) error {
	cli, err := getClientFor(idOrName)

	if err != nil {
		return err
	}

	return cli.RestartContainer(idOrName, 3)
}

// Stop container
func Stop(idOrName string) error {
	cli, err := getClientFor(idOrName)

	if err != nil {
		return err
	}

	return cli.StopContainer(idOrName, 3)
}

func GetAllImages() {

}

func GetAllContainers() {

}

func GetAllExternalPorts() {

}

func GetNetwork(idOrName string) {

}

func GetInternalIP(idOrName string) {

}

func getClientFor(idOrName string) (*docker.Client, error) {
	err := checkIdOrName(idOrName)

	if err != nil {
		return nil, err
	}

	cli, err := getDockerClient()

	if err != nil {
		return nil, err
	}

	return cli, nil
}

func checkIdOrName(idOrName string) error {
	if len(strings.TrimSpace(idOrName)) == 0 {
		return errors.New("container id or name not provided")
	}

	return nil
}

func getDockerClient() (*docker.Client, error) {
	endpoint := S.Ctx.DockerSockDir

	if strings.HasSuffix(endpoint, ".sock") {
		endpoint = strings.Join([]string{"unix:", endpoint}, "/")
	}

	return docker.NewClient(endpoint)
}
