use_script("utils.lua");
use_script("rotate.lua");

BELT_DEFAULT_COLOR_MAP = {};
BELT_DEFAULT_COLOR_MAP[color_from_rgb(0xFF, 0x00, 0x00)] = color_from_rgb(68, 68, 68);
BELT_DEFAULT_COLOR_MAP[color_from_rgb(0x00, 0xFF, 0x00)] = color_from_rgb(79, 79, 79);
BELT_DEFAULT_COLOR_MAP[color_from_rgb(0x00, 0x00, 0xFF)] = color_from_rgb(89, 89, 89);
BELT_DEFAULT_COLOR_MAP[color_from_rgb(0xFF, 0x00, 0xFF)] = color_from_rgb(97, 97, 97);

BELT_DEFAULT_ACTIVE_LIGHT_MAP = {};
BELT_DEFAULT_ACTIVE_LIGHT_MAP[color_from_rgb(0xFF, 0x00, 0x00)] = 0;
BELT_DEFAULT_ACTIVE_LIGHT_MAP[color_from_rgb(0x00, 0xFF, 0x00)] = 0;
BELT_DEFAULT_ACTIVE_LIGHT_MAP[color_from_rgb(0x00, 0x00, 0xFF)] = color_from_rgba(0, 102, 0, 0);
BELT_DEFAULT_ACTIVE_LIGHT_MAP[color_from_rgb(0xFF, 0x00, 0xFF)] = color_from_rgba(0, 255, 0, 0);

function export_belt(beltColorMap, activeLightMap, maskModifierFunc, frameModifierFunc, getStateName)
    maskModifierFunc = maskModifierFunc or function() end;
    frameModifierFunc = frameModifierFunc or function() end;
    getStateName = getStateName or function(activeFlagName, orient, frameOffset)
        return activeFlagName .. get_side_name(orient) .. frameOffset;
    end;

    for meta = 0, 31 do
        local active = (meta & (1 << 4)) ~= 0;
        local frameOffset = (meta >> 2) & 3;
        local orient = meta & 3;
    
        local activeFlagName = "inactive";
        if active then
            activeFlagName = "active";
        end
    
        local stateName = getStateName(activeFlagName, orient, frameOffset);
    
        local collisionMask = rotate_sprite(vsp_from_assets("templates/belts/mask.vsp"), orient);
        maskModifierFunc(active, orient, collisionMask);
        set_collision_mask(stateName, collisionMask);
    
        local templ = rotate_sprite(vsp_from_assets("templates/belts/belt" .. frameOffset .. ".vsp"), orient);

        local colormap = vsp_clone(templ);
        vsp_color_remap(colormap, beltColorMap);

        local lightspecmap = vsp_clone(templ);
        vsp_color_remap_with_default(lightspecmap, activeLightMap, 0);

        if not active then
            vsp_fill(lightspecmap, 0);
        end

        frameModifierFunc(active, orient, frameOffset, colormap, lightspecmap);

        export_frame(stateName, {
            colormap = colormap,
            lightspecmap = lightspecmap,
        });
    end
end