import datetime
import os
import cv2
import base64


def read_image_to_base64(file_path):
    with open(file_path, "rb") as img_file:
        img_data = img_file.read()
        base64_encoded = base64.b64encode(img_data).decode('utf-8')
    return base64_encoded


def read_images_in_folder(folder_path):
    image_files = [f for f in os.listdir(
        folder_path) if os.path.isfile(os.path.join(folder_path, f))]
    base64_images = []

    for file in image_files:
        file_path = os.path.join(folder_path, file)
        if file_path.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')):
            base64_images.append({
                "filename": file,
                "base64": read_image_to_base64(file_path)
            })
    return base64_images


def save_images(img_list, folder):
    if not os.path.exists(folder):
        os.makedirs(folder)
    now = datetime.datetime.now()
    date_str = now.strftime("%Y-%m-%d")
    folder_path = os.path.join(folder, date_str)
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)
    time_str = now.strftime("%H_%M_%S")
    for idx, img in enumerate(img_list):
        image_number = idx + 1
        filename = f"{time_str}_{image_number}.jpg"
        save_path = os.path.join(folder_path, filename)
        cv2.imwrite(save_path, img[..., ::-1])


def read_img_result(img_list):
    res = []
    for _, img in enumerate(img_list):
        _, img_encoded = cv2.imencode('.jpg', img)
        # Encode image as base64
        base64_encoded = base64.b64encode(img_encoded).decode('utf-8')
        res.append(base64_encoded)
    return res


def check_channels(image):
    channels = image.shape[2] if len(image.shape) == 3 else 1
    if channels == 1:
        image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
    elif channels > 3:
        image = image[:, :, :3]
    return image


def resize_image(img, max_length=768):
    height, width = img.shape[:2]
    max_dimension = max(height, width)

    if max_dimension > max_length:
        scale_factor = max_length / max_dimension
        new_width = int(round(width * scale_factor))
        new_height = int(round(height * scale_factor))
        new_size = (new_width, new_height)
        img = cv2.resize(img, new_size)
    height, width = img.shape[:2]
    img = cv2.resize(img, (width-(width % 64), height-(height % 64)))
    return img
