from .ImageManipulation import ImageManipulation
from ImageContainer import ImageContainer
from typing import Any, List
from utils.image_utils import pil_to_cv2, cv2_to_pil
import cv2
import numpy as np


class ColorAdjust(ImageManipulation):
    def getManipulationName(self) -> str:
        return "Color Adjust"

    def getParameters(self) -> List[str]:
        return ["brightness", "contrast", "saturation"]

    def manipulateImage(self, image: ImageContainer, parameters: Any) -> None:
        if image is None or image.getImage() is None:
            return
        pil_img = image.getImage()
        cv_img = pil_to_cv2(pil_img)

        brightness = 0.0
        contrast = 1.0
        saturation = 1.0

        if isinstance(parameters, dict):
            if parameters.get("brightness") is not None:
                brightness = float(parameters.get("brightness"))  # -100..100 (additive)
            if parameters.get("contrast") is not None:
                contrast = float(parameters.get("contrast"))      # 0.0..3.0 (multiplicative)
            if parameters.get("saturation") is not None:
                saturation = float(parameters.get("saturation"))  # 0.0..3.0 (multiplicative)

        # Apply brightness/contrast on BGR
        adjusted = cv2.convertScaleAbs(cv_img, alpha=contrast, beta=brightness)

        # Adjust saturation in HSV
        hsv = cv2.cvtColor(adjusted, cv2.COLOR_BGR2HSV).astype(np.float32)
        h, s, v = cv2.split(hsv)
        s = np.clip(s * saturation, 0, 255)
        hsv = cv2.merge([h, s, v]).astype(np.uint8)
        result = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)

        image._imageData = cv2_to_pil(result)

