from pathlib import Path

import cv2
import numpy as np

from app.exceptions import SaveImageError
from app.utils.format import create_safe_string


class ImageSaver:
    """
    Module for saving images.
    """

    def __init__(self, folder: Path) -> None:
        self.folder = folder

    def save(self, image: np.ndarray, file_name: str, extension: str = "png") -> Path:
        """
        Saves image to the folder with given file name and extension.
        :param image: numpy array with image data
        :param file_name: name of the file
        :param extension: extension of the file
        :return: path object to the saved file
        """
        safe_file_name = create_safe_string(file_name)
        file_path = self.folder / f"{safe_file_name}.{extension}"
        try:
            is_saved = cv2.imwrite(str(file_path), image)
        except cv2.error as ex:
            raise SaveImageError(f"Failed to save image: {file_path}") from ex
        if not is_saved:
            raise SaveImageError(f"Failed to save image: {file_path}")
        return file_path
