import os
from pathlib import Path

import bpy
from mathutils import Vector


unit = 500

# .5 to align the image to the grid, else the center of the image will be at the origin
# num_of_images in x / 2 and negate to push to the left
x_offset = (-6 + .5) * unit
# num_of_images in x / 2 and negate to push up
y_offset = (5 + .5) * unit



folder = Path(r"E:\IV\radar")
radar_collection_name = "Radar"

blank_chunk = folder / "radar16" / "radar16.dds" # blank enough

if radar_collection_name not in bpy.data.collections:
    collection = bpy.data.collections.new(radar_collection_name)
    bpy.context.scene.collection.children.link(collection)
radar_collection = bpy.data.collections[radar_collection_name]

location = Vector((x_offset + unit, y_offset, 0))
radar_chunks = list(os.listdir(folder))

index = 1
while index <= 120:
    name = f"radar{index}"
    if name not in radar_chunks:
        img = bpy.data.images.get(blank_chunk.name, bpy.data.images.load(str(blank_chunk)))
    else:
        img_path = folder / name / (name + '.dds')
        img = bpy.data.images.get(img_path.name, bpy.data.images.load(str(img_path)))

    empty = radar_collection.objects.get(name)
    if empty is None:
        empty = bpy.data.objects.new(name, None)
        radar_collection.objects.link(empty)

    
    empty.location = location
    empty.empty_display_size = unit
    empty.empty_display_type = 'IMAGE'
    empty.data = img

    
    if not index % 12:
        location.x = x_offset
        location.y -= unit
    location.x += 1 * unit
    index+=1
    
    