const std = @import("std");
const r = @import("raylib.zig");
const assets = @import("assets.zig");

pub usingnamespace @cImport(@cInclude("tmx.h"));

const tmx = @This();

pub fn texLoad(path: [*c]const u8) callconv(.C) ?*anyopaque {
    const data = assets.getTexture(std.mem.span(path)) catch return null;
    const tex: *r.Texture2D = std.heap.page_allocator.create(r.Texture2D) catch return null;
    tex.* = data;
    return @as(?*anyopaque, @ptrCast(tex));
}

pub fn texFree(tex: ?*anyopaque) callconv(.C) void {
    if (tex != null) {
        const t = @as(*r.Texture2D, @alignCast(@ptrCast(tex.?)));
        r.UnloadTexture(t.*);
        std.heap.page_allocator.destroy(t);
    }
}

pub const Property = union(enum) {
    none,
    integer: i32,
    decimal: f32,
    boolean: bool,
    string: []u8,
    color: r.Color,
    file: []u8,
    object_id: c_int,
    //properties: tmx.str,
};

// pub fn getProperties(hash: ?*tmx.tmx_properties) []Property{
//     const props = tmx.tmx_property_foreach(hash: ?*tmx_properties, callback: tmx_property_functor, userdata: ?*anyopaque)
// }

pub fn getProperty(hash: ?*tmx.tmx_properties, key: [*c]const u8) Property {
    const prop = tmx.tmx_get_property(hash, key);
    if (prop == null) return .none;
    const ret: Property = switch (prop.*.type) {
        tmx.PT_NONE => .none,
        tmx.PT_INT => Property{ .integer = @intCast(prop.*.value.integer) },
        tmx.PT_FLOAT => Property{ .decimal = prop.*.value.decimal },
        tmx.PT_BOOL => Property{ .boolean = prop.*.value.boolean == 0 },
        tmx.PT_STRING => Property{ .string = std.mem.span(prop.*.value.string) },
        tmx.PT_COLOR => Property{ .color = r.getTmxColor(prop.*.value.color) },
        tmx.PT_FILE => Property{ .file = assets.get(std.mem.span(prop.*.value.file)) catch "" },
        tmx.PT_OBJECT => Property{ .object_id = prop.*.value.object_id },
        tmx.PT_CUSTOM => .none, //ret.properties = prop.*.value.properties,
        else => .none,
    };
    return ret;
}
