package internal

import (
	"fmt"
	log "github.com/sirupsen/logrus"
	"strings"
)

type Layer struct {
	Image
	os      string
	arch    string
	variant string
}

func (layer *Layer) String() string {
	return fmt.Sprintf("%s : os %s, arch %s, variant %s", layer.Image.String(), layer.os, layer.arch, layer.variant)
}

func (layer *Layer) CreateLayer(registry Registry, buildDir string, buildOpt string) {
	if buildOpt != "" {
		buildOpt = fmt.Sprintf("build --platform %s %s -t", layer.toPlatform(), buildOpt)
	} else {
		buildOpt = fmt.Sprintf("build --platform %s -t", layer.toPlatform())
	}

	// $(OCI_CLI_BUILD) build --platform $(2) -t $(REGISTRY_IP):5000/$(1):$(3) .
	if stdout, err := runOciCli("docker", "buildx", buildOpt, registry, layer.Image, buildDir); err != nil {
		log.Fatalf("layer build step failed : %v%v", stdout, err)
	} else {
		log.Debug(stdout)
	}

	// $(OCI_CLI) push $(REGISTRY_IP):5000/$(1):$(3)
	if stdout, err := runOciCli("docker", "push", "", registry, layer.Image); err != nil {
		log.Fatalf("layer build step failed : %v%v", stdout, err)
	} else {
		log.Debug(stdout)
	}
}

func (layer *Layer) toPlatform() Platform {
	if layer.variant != "" {
		return Platform(fmt.Sprintf("%s/%s/%s", layer.os, layer.arch, layer.variant))
	} else {
		return Platform(fmt.Sprintf("%s/%s", layer.os, layer.arch))
	}
}

type Layers []Layer

func NewLayers(imageName string, platforms []Platform) Layers {
	var layers Layers
	for _, platform := range platforms {
		splitPlatform := strings.Split(string(platform), "/")

		var layer Layer
		if len(splitPlatform) < 3 {
			layer = Layer{
				Image: Image{
					imageName,
					fmt.Sprintf("%s-%s", splitPlatform[0], splitPlatform[1]),
				},
				os:   splitPlatform[0],
				arch: splitPlatform[1],
			}
		} else {
			layer = Layer{
				Image: Image{
					imageName,
					fmt.Sprintf("%s-%s%s", splitPlatform[0], splitPlatform[1], splitPlatform[2]),
				},
				os:      splitPlatform[0],
				arch:    splitPlatform[1],
				variant: splitPlatform[2],
			}
		}

		layers = append(layers, layer)
	}

	return layers
}