from pathlib import Path
import os
os.environ["OPENCV_IO_ENABLE_OPENEXR"]="1"
import cv2
import numpy as np
import re
import skimage
import skimage.io
import torch

def imread(path):
    """
    Reads an image from a path.
    """
    # read float value instead of uint8
    img = cv2.imread(path, cv2.IMREAD_UNCHANGED)
    img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
    return img


def read_images(path, ext='.exr'):
    """
    Reads all images from a path.
    """
    def tryint(s):
        try:
            return int(s)
        except:
            return s

    def alphanum_key(s):
        return [tryint(c) for c in re.split('([0-9]+)', s)]

    images = []
    files = os.listdir(path)
    files.sort(key=alphanum_key)
    for f in files:
        if f.endswith(ext):
            images.append(imread(os.path.join(path, f)))
    return images


def imwrite(img, path):
    """
    Writes an image to a path.
    """
    if path.endswith('.png'):
        img = img.astype(np.float32)
        img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
        img = np.power(img, 1/2.2)
        img = np.uint8(np.clip(img * 255., 0., 255.))
        cv2.imwrite(path, img)
    if path.endswith('.exr'):
        img = img.astype(np.float32)
        img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
        cv2.imwrite(path, img)

def mkdir(path):
    """
    makes a directory if it doesn't exist
    """
    Path(path).mkdir(parents=True, exist_ok=True)


class cd:
    """Context manager for changing the current working directory"""

    def __init__(self, newPath):
        self.newPath = os.path.expanduser(newPath)

    def __enter__(self):
        self.savedPath = os.getcwd()
        os.chdir(self.newPath)

    def __exit__(self, etype, value, traceback):
        os.chdir(self.savedPath)
