import os
import warnings
import json
import numpy as np
from PIL import Image

WORKING_DIR = os.path.join("py_scripts","block_color_extraction")
INPUT_DIR = 'blocks_1.20.2'
FILETYPE = '.json'

def get_average_color(img_array):
    img_color = np.mean(img_array, axis=(0, 1))
    img_color = tuple(img_color.astype(int))
    return img_color

# def get_weighted_average_color(img_array):
#     # Split into RGBA channels
#     a = img_array[:, :, 3]
    
#     total_weight = np.sum(a)/255
#     weighted_sum = np.sum(img_array[:, :, :3] * a[..., np.newaxis], axis=(0, 1))
    
#     img_color = (0, 0, 0)
#     # Handle potential division by zero (fully transparent image)
#     if total_weight != 0:
#         weighted_avg = weighted_sum / total_weight
#         img_color = tuple(weighted_avg.astype(int))
    
#     return img_color

def process_images(images):
    block_data = []
    fail_count = 0
    # cycle through the images starting from the LAST one until -1 is reached
    i = len(images) -1
    while i >= 0:
        img_name = images[i]

        # try to open an image
        try:  
            img = Image.open(os.path.join(WORKING_DIR, INPUT_DIR, img_name))
            img = img.convert('RGBA')
            img_array = np.array(img)
            
            img_color = get_average_color(img_array)
            img_id = img_name.split('.')[0]
            block_data.append({
                    'name': img_id,
                    'rgb': '#{:02x}{:02x}{:02x}'.format(*img_color)
                })

        # skip to the next image if the current one cannot be processed
        except:  
            warnings.warn(f'Warning! Cannot be proces "{img_name}".')
            fail_count += 1

        # substract 1 to go to the next image
        i -= 1
    
    print(f"{len(images) -fail_count}/{len(images)} textures converted.")    
    return block_data

print("Starting conversion.")

images = [f for f in os.listdir(os.path.join(WORKING_DIR,INPUT_DIR)) if f.endswith('.png')]
block_data = process_images(images)

with open(os.path.join(WORKING_DIR, INPUT_DIR + FILETYPE), 'w') as f:
    json.dump(block_data, f, indent=4)

print()
print('Conversion finished successfuly.')

