--[[
Export images and slice coordinate data for Poink-and-Clink game template.

All exported data will be placed in a directory named "aseprite-export" alongside the aseprite file being exported, according to the following directory structure:

filename.aseprite
aseprite-export/
    images/
        filename.layer1.tag1.gif
        filename.layer1.tag2.gif
        ... etc.
    ink/
        filename.ink

IMAGE DATA NOTES:

The tag named "default" will be omitted from the generated filename
    (i.e. filename.layer1.gif will be the "default" animation of layer1).
Layer groups will be exported collectively as a single layer.
Try not to include spaces in layer or tag names.

SLICE DATA NOTES:

A slice named "example" spanning from 0,0 to 10,10 with metadata "hovertext" will be exported in ink as:

VAR C_example = "0,0,10,10 hovertext"

]]--

local SKIP_UI = false
if app.params["SKIP_UI"] == "1" then
    -- Lets us skip showing UI elements (would otherwise crash in batch mode)
    -- To use, run aseprite with --script-param SKIP_UI
    SKIP_UI = true
end

local sprite = app.activeSprite

-- (returns list of what the visibility was originally, so we can restore).
local function hideAllLayers(layers)
  visibility_record = {}
  for index, layer in ipairs(layers) do
    visibility_record[index] = layer.isVisible
    layer.isVisible = false
  end
  return visibility_record
end

local function resetVisibility(layers,settings)
  for index, layer in ipairs(layers) do
    layer.isVisible = visibility_record[index]
  end
end

-- export a gif of the given layer and tag
local function exportLayerTag(image_dir, scene, layer, tag)
    local filename = scene .. "." .. layer.name .. "." .. tag.name .. ".gif"
    if tag.name == "default" then
        -- omit "tag" part of filename
        filename = scene .. "." .. layer.name .. ".gif"
    end
    local full_path = app.fs.joinPath(image_dir, filename)
    
    -- Note: transaction/undo didn't seem to work for layer visibility,
    ---  I guess because changing layer visibility is not a "command"?
    local prev_visibility = hideAllLayers(sprite.layers)
    layer.isVisible = true
    app.command.SaveFileCopyAs{
        ui=false,
        filename=full_path,
        tag=tag.name,
    }
    resetVisibility(sprite.layers, prev_visibility)
end

-- TODO implement this
local function exportInkData(filename, scene_title)
    local ink_content = [[
// Auto-generated by Poink-and-Clink exporter for Aseprite.
// Do not modify this file - your changes will be overwritten when exporting!

]]
    for i, slice in ipairs(sprite.slices) do
        local s = string.format("VAR %s = \"%d,%d,%d,%d %s\"\n",
            "C_" .. slice.name:gsub(" ","_"),
            slice.bounds.x,
            slice.bounds.y,
            slice.bounds.x + slice.bounds.width,
            slice.bounds.y + slice.bounds.height,
            slice.data
        )
        ink_content = ink_content .. s
    end

    local file = io.open(filename,"w")
    if file then
        file:write(ink_content)
    else
        print("Error: unable to save file: " .. filename)
    end
end

local function main()
    -- Confirmation dialog 

    if not SKIP_UI then
        local dialog = Dialog()
        dialog:label{ id="label", text="Export poink-and-clink data?" }
        dialog:button{ id="ok", text="Export" }
        dialog:button{ id="cancel", text="Cancel", onclick = function() dialog:close() end }
        dialog:show()

        if not dialog.data.ok then
            return
        end
    end
    
    -- Export details:
    --  create "aseprite-export" dir in same directory as .aseprite file
    --  within that, create "images" and "ink"
    --  this should be the most practical setup, I think
    local scene_title = app.fs.fileTitle(sprite.filename)
    local file_dir = app.fs.filePath(sprite.filename)
    local export_dir = app.fs.joinPath(file_dir,"aseprite-export")
    local image_dir = app.fs.joinPath(export_dir,"images")
    local ink_dir = app.fs.joinPath(export_dir,"ink")
    
    local result1 = app.fs.makeAllDirectories(image_dir)
    local result2 = app.fs.makeAllDirectories(ink_dir)
    if not (result1 and result2) then
        print("Error creating directories")
        return
    end
    
    -- Export images
    for i,tag in ipairs(sprite.tags) do
        for i,layer in ipairs(sprite.layers) do
            --TODO maybe extra checks to minimize unecessary exports
            exportLayerTag(image_dir, scene_title, layer, tag)
        end
    end

    -- Export ink
    local ink_filename = app.fs.joinPath(ink_dir,scene_title .. ".ink")
    exportInkData(ink_filename)

    if not SKIP_UI then
        print("Export completed")
    end
end

main()
