import os
import random
os.environ["MKL_NUM_THREADS"] = "1"  # noqa F402
os.environ["NUMEXPR_NUM_THREADS"] = "1"  # noqa F402
os.environ["OMP_NUM_THREADS"] = "1"  # noqa F402

import numpy as np
from PIL import Image  
import cv2

import torch
import torch.utils.data as data
from torchvision import transforms
import pdb
import math
import torchvision.transforms as T

cv2.setNumThreads(0)

def pil_loader(path):
    with open(path, 'rb') as f:
        with Image.open(f) as img:
            return img.convert('RGB')


class MonoDataset(data.Dataset):
    """Superclass for monocular dataloaders
    """
    def __init__(self,
                 data_path,
                 filenames,
                 height,
                 width,
                 frame_idxs,
                 num_scales,
                 is_train=False,
                 img_ext='.jpg',
                 stereo_split=False):
        super(MonoDataset, self).__init__()

        self.data_path = data_path
        self.filenames = filenames
        self.height = height
        self.width = width
        self.num_scales = num_scales
        self.stereo_split = stereo_split
        self.interp = T.InterpolationMode.LANCZOS
        self.frame_idxs = frame_idxs
        self.is_train = is_train
        self.img_ext = img_ext
        self.loader = pil_loader
        self.to_tensor = transforms.ToTensor()

        self.resize = {}
        for i in range(self.num_scales):
            s = 2 ** i
            self.resize[i] = transforms.Resize((self.height // s, self.width // s),
                                            interpolation=self.interp)


    def preprocess(self, inputs):
        """Resize colour images to the required scales and augment if required

        We create the color_aug object in advance and apply the same augmentation to all
        images in this item. This ensures that all images input to the pose network receive the
        same augmentation.
        """

        for k in list(inputs):
            if ("color" in k) or ("augmented" in k):
                n, im, i = k
                for i in range(self.num_scales):
                    if n == "color":
                        inputs[(n, im, i)] = self.resize[i](inputs[(n, im, i - 1)]) # n = color
                        # inputs[("scale_aug", im, i)] = inputs[(n, im, i)] # n = color

        for k in list(inputs):
            f = inputs[k]
            if ("color" in k):
                n, im, i = k
                inputs[(n, im, i)] = self.to_tensor(f)
                
    def __len__(self):
        target_list = ['AdaWaymo', 'AdaDrivingStereo']
        if not type(self).__name__ in target_list:
            return len(self.filenames)
        return len(self.filenames[1:-1])

    def load_intrinsics_kitti(self, folder, frame_index):
        return self.K.copy()

    def __getitem__(self, index):
        """Returns a single training item from the dataset as a dictionary.

        Values correspond to torch tensors.
        Keys in the dictionary are either strings or tuples:

            ("color", <frame_id>, <scale>)          for raw colour images,
            ("color_aug", <frame_id>, <scale>)      for augmented colour images,
            ("K", scale) or ("inv_K", scale)        for camera intrinsics,

        <frame_id> is:
            an integer (e.g. 0, -1, or 1) representing the temporal step relative to 'index',

        <scale> is an integer representing the scale of the image relative to the fullsize image:
            -1      images at native resolution as loaded from disk
            0       images resized to (self.width,      self.height     )
            1       images resized to (self.width // 2, self.height // 2)
            2       images resized to (self.width // 4, self.height // 4)
            3       images resized to (self.width // 8, self.height // 8)
        """
        inputs = {}

        height_re=0
        width_re=0
        dx=0
        dy=0
        box_HiS = 0
        
        poses = {}

        if type(self).__name__ == "KITTIRAWDataset" or type(self).__name__ == "KITTIOdomDataset":
            inputs["dataset"] = 0
            if self.is_robust_test:
                folder, frame_index, side, spec = self.index_to_folder_and_frame_idx(index)
                if self.robust_augment != None:
                    spec = self.robust_augment
            else:
                folder, frame_index, side, _ = self.index_to_folder_and_frame_idx(index)
            for i in self.frame_idxs:
                if i == "s":
                    other_side = {"r": "l", "l": "r"}[side]
                    inputs[("color", i, -1)] = self.get_color(
                        folder, frame_index, other_side, "data", do_flip)
                else:
                    try:
                        if self.is_robust_test:
                            inputs[("color", i, -1)] = self.get_color(folder, frame_index + i, side, spec, do_flip)
                        else:
                            inputs[("color", i, -1)] = self.get_color(folder, frame_index + i, side, "data", do_flip)
                        if self.is_train or self.robust_val:
                            inputs[("augmented", i, -1)] = self.get_color(folder, frame_index + i, side, spec, do_flip)
                    except FileNotFoundError as e:
                        if i != 0:
                            # fill with dummy values
                            inputs[("color", i, -1)] = Image.fromarray(np.zeros((100, 100, 3)).astype(np.uint8))
                            if self.is_train or self.robust_val:
                                inputs[("augmented", i, -1)] = Image.fromarray(np.zeros((100, 100, 3)).astype(np.uint8))
                            poses[i] = None
                        else:
                            raise FileNotFoundError(f'Cannot find frame - make sure your '
                                                    f'--data_path is set correctly, or try adding'
                                                    f' the --png flag. {e}')
            for scale in range(self.num_scales):
                K = self.load_intrinsics_kitti(folder, frame_index)
                K[0, :] *= self.width // (2 ** scale)
                K[1, :] *= self.height // (2 ** scale)
                inv_K = np.linalg.pinv(K)
                inputs[("K", scale)] = torch.from_numpy(K)
                inputs[("inv_K", scale)] = torch.from_numpy(inv_K)
        elif type(self).__name__ == 'WAYMO':
            inputs[("color", 0, -1)] = self.get_color(self.filenames[index])

        elif type(self).__name__ == "DRIVINGSTEREO":
            num_frames = len(self.frame_idxs)
            if num_frames == 1:
                inputs[("color", 0, -1)] = self.get_color(self.filenames[index], self.stereo_split)
            elif num_frames == 3:
                idx_helper = [i for i in range(1, len(self.filenames)-1)]
                for i in self.frame_idxs:
                    inputs[("color", i, -1)] = self.get_color(self.filenames[idx_helper[index]+i], self.stereo_split)
                for scale in range(self.num_scales):
                    K = self.K.copy()
                    K[0, :] *= width_re // (2 ** scale)
                    K[1, :] *= height_re // (2 ** scale)
                    inv_K = np.linalg.pinv(K)
                    inputs[("K", scale)] = torch.from_numpy(K)
                    inputs[("inv_K", scale)] = torch.from_numpy(inv_K)
        
        self.preprocess(inputs)
        for i in self.frame_idxs:
            del inputs[("color", i, -1)]
            del inputs[("color", i, 1)]
            del inputs[("color", i, 2)]
            del inputs[("color", i, 3)]
            if self.is_train:
                del inputs[("augmented", i, -1)]
                del inputs[("augmented", i, 0)]
                del inputs[("augmented", i, 1)]
                del inputs[("augmented", i, 2)]
                del inputs[("augmented", i, 3)]            

        return inputs

    def get_color(self, folder, frame_index, side, do_flip):
        raise NotImplementedError
    
    def check_depth(self):
        raise NotImplementedError

    def get_depth(self, folder, frame_index, side, do_flip):
        raise NotImplementedError
