package util

import (
	"openquell/config"
	"path/filepath"
	"strings"

	"github.com/solarlune/ldtkgo"
)

type TileSetSubRect struct {
	X, Y, W, H int
}

func Map2Subrect(raw map[string]any) *TileSetSubRect {
	// we need to translate this map for less typing
	return &TileSetSubRect{
		W: int(raw["w"].(float64)),
		H: int(raw["h"].(float64)),
		X: int(raw["x"].(float64)),
		Y: int(raw["y"].(float64)),
	}
}

func GetPropertyRef(entity *ldtkgo.Entity) string {
	ref := entity.PropertyByIdentifier(config.LDTK_Entity_Ref)
	if ref != nil {
		if ref.Value != nil {
			refid := ref.Value.(map[string]interface{})
			ref := refid["entityIid"].(string)

			if ref != "" {
				return ref
			}
		}
	}

	return ""
}

func GetPropertyString(entity *ldtkgo.Entity, property string) string {
	ref := entity.PropertyByIdentifier(property)
	if ref != nil {
		return ref.AsString()
	}

	return ""
}

func GetPropertyBool(entity *ldtkgo.Entity, property string) bool {
	ref := entity.PropertyByIdentifier(property)
	if ref != nil {
		return ref.AsBool()
	}

	return false
}

func GetPropertyEnum(entity *ldtkgo.Entity, property string) string {
	ref := entity.PropertyByIdentifier(property)
	if ref != nil {
		return ref.AsString()
	}

	return ""
}

func GetPropertyToggleTile(entity *ldtkgo.Entity) *TileSetSubRect {
	ref := entity.PropertyByIdentifier(config.LDTK_Toggle_Tile)
	if ref != nil {
		return Map2Subrect(ref.AsMap())
	}

	return nil
}

func GetBGImage(plan *ldtkgo.Level) string {
	return filepath.Base(strings.TrimSuffix(plan.BGImage.Path, ".png"))
}
