_HEADER_COMMENT = "// This file was generated by img2gb, DO NOT EDIT\n\n"


def tileset_to_c(tileset, tilemap=None, name="tileset"):
    c = _HEADER_COMMENT
    c += "#include <types.h>\n\n"
    c += "const UINT8 %s[] = {\n" % name.upper()
    for tile in tileset.tiles:
        c += "    %s,\n" % ", ".join(["0x%02X" % b for b in tile.data])
    c += "};\n"
    if tilemap:
        c += "\nconst UINT8 %s_MAP[] = {\n" % name.upper()
        for index in range(len(tilemap.map)):
            if index % tilemap.width == 0:
                c += "    "
            tile_id = tilemap.map[index]
            c += "0x%02X," % tile_id
            if (index + 1) % tilemap.width == 0:
                c += "\n"
            else:
                c += " "
        c += "};\n"
    return c


def tileset_to_h(tileset, tilemap=None, name="tileset"):
    h = _HEADER_COMMENT
    h += "#ifndef _%s_H\n" % name.upper()
    h += "#define _%s_H\n\n" % name.upper()
    h += "extern const UINT8 %s[];\n" % name.upper()
    h += "#define %s_TILE_COUNT %i\n" % (name.upper(), tileset.length)
    if tilemap:
        h += "\nextern const UINT8 %s_MAP[];\n" % name.upper()
        h += "#define %s_MAP_WIDTH %i\n" % (name.upper(), tilemap.width)
        h += "#define %s_MAP_HEIGHT %i\n" % (name.upper(), tilemap.height)
    h += "\n#endif\n"
    return h
