package bundler

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"

	"github.com/chaposcripts/lubu/config"
)

const RESOURCE_WRITE_FUNCTION = `-- This function generated by LuBu. Used to create compressed resource
local function LUBU_CREATE_RESOURCE_FILE(path, bytes)
	local file = io.open(path, "wb");
	assert(file, '[LuBu Error] Error loading compressed dynamic library (counld not open file): ' .. path);
	for _, byte in ipairs(bytes) do
		file:write(string.char(byte));
	end
	file:close();
end`

func GenerateResources(basePath string, config config.Config) string {
	var lines []string = []string{}
	if len(config.Resource) > 0 {
		lines = append(lines, "\n-- Bundled Resources\n"+RESOURCE_WRITE_FUNCTION)
		for userPath, devPath := range config.Resource {
			lines = append(lines, GenerateResourceFile(basePath, userPath, devPath))
		}
	}
	return strings.Join(lines, "\n")
}

func GenerateResourceFile(basePath, userPath, devPath string) string {
	fullPath := filepath.Join(basePath, devPath)
	log.Printf("Packing resource \"%s\" from: %s", userPath, fullPath)
	bytes, err := os.ReadFile(fullPath)
	if err != nil {
		log.Fatalf("Error reading resource %s: %s", fullPath, err.Error())
	}
	byteAsLuaString := []string{}
	for _, _byte := range bytes {
		byteAsLuaString = append(byteAsLuaString, fmt.Sprintf("%d", _byte))
	}

	return fmt.Sprintf("\n-- Resource \"%s\" (from %s)\nLUBU_CREATE_RESOURCE_FILE('%s', { %s });", userPath, fullPath, userPath, strings.Join(byteAsLuaString, ", "))
}
