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


class RotateImage(ImageManipulation):
    def getManipulationName(self) -> str:
        return "Rotate"

    def getParameters(self) -> List[str]:
        return ["angle"]

    def manipulateImage(self, image: ImageContainer, parameters: Any) -> None:
        if image is None or image.getImage() is None:
            return
        pil_img = image.getImage()
        angle = 90
        if isinstance(parameters, dict) and parameters.get("angle") is not None:
            angle = int(parameters.get("angle"))
        cv_img = pil_to_cv2(pil_img)
        (h, w) = cv_img.shape[:2]
        center = (w // 2, h // 2)
        M = cv2.getRotationMatrix2D(center, angle, 1.0)
        rotated = cv2.warpAffine(cv_img, M, (w, h), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT)
        image._imageData = cv2_to_pil(rotated)

