# note for davis dataloader later: temporally consistent depth estimator: https://github.com/yu-li/TCMonoDepth
# note for cool idea of not even downloading data and just streaming from youtube:https://gist.github.com/Mxhmovd/41e7690114e7ddad8bcd761a76272cc3
import matplotlib.pyplot as plt; 
import cv2
import os
import multiprocessing as mp
import torch.nn.functional as F
import torch
import random
import imageio
import numpy as np
from glob import glob
from collections import defaultdict
from pdb import set_trace as pdb
from itertools import combinations
from random import choice
import matplotlib.pyplot as plt
import imageio.v3 as iio

from torchvision import transforms

import sys

from glob import glob
import os
import gzip
import json
import numpy as np
from data import common

from einops import rearrange, repeat
ch_sec = lambda x: rearrange(x,"... c x y -> ... (x y) c")
hom = lambda x, i=-1: torch.cat((x, torch.ones_like(x.unbind(i)[0].unsqueeze(i))), i)

class DAVIS(torch.utils.data.Dataset):
    """Dataset for a class of objects, where each datapoint is a SceneInstanceDataset."""

    def __init__(
        self,
        n_skip=1,
        num_trgt=1,
        low_res=(96,112),
        path=".",
        val=False,
    ):

        self.n_trgt=num_trgt
        self.val=val
        self.num_skip=n_skip
        self.low_res=torch.tensor(low_res)

        self.scenes = sorted(glob("/data/DAVIS/1080p/*"))

    def __len__(self):
        return len(self.scenes)#-self.n_trgt*self.num_skip[0]-1

    def collate_fn(self, batch_list):
        keys = batch_list[0].keys()
        result = defaultdict(list)

        for entry in batch_list:
            # make them all into a new dict
            for key in keys:
                result[key].append(entry[key])

        for key in keys:
            try:
                result[key] = torch.stack(result[key], dim=0)
            except:
                continue

        return result

    def __getitem__(self, idx,seq_query=None):

        images = sorted(glob(self.scenes[idx]+"/*"))[:40]

        idx=0

        context = []
        trgt = []
        post_input = []

        n_skip = self.num_skip + 1
        frames = torch.stack([torch.from_numpy(plt.imread(images[idx+i*n_skip])).float().permute(2,0,1) for i in range(self.n_trgt)])

        if frames.max()>2: frames=frames/255

        org_ratio=frames[0].size(-2)/frames[0].size(-1)
        h,s=3,1
        hi_res=[640, 1024]
        return common.make_sample({"rgb":frames* 2-1,"org_ratio":org_ratio},1/org_ratio,hires_factor=h,budget=192*640/(8//s),low_res=[160*1,256*1] if 1 else hi_res,hi_res=hi_res)
