import os
import os.path
import torch
import json
import pickle
import numpy as np
import sys
import torchvision.transforms as transforms
from progressbar import ProgressBar
import pdb

def pc_normalize(pc):
    l = pc.shape[0]
    centroid = np.mean(pc, axis=0)
    pc = pc - centroid
    m = np.max(np.sqrt(np.sum(pc**2, axis=1)))
    pc = pc / m
    return pc

class ShapeNetPart():
    def __init__(self, root, num_points = 2048, split='train', normalize=True, transforms = None, all_points=False):
        self.transforms = transforms
        self.num_points = num_points
        self.root = root
        self.catfile = os.path.join(self.root, 'synsetoffset2category.txt')
        self.normalize = normalize
        self.all_points = all_points

        self.cat = {}
        with open(self.catfile, 'r') as f:
            for line in f:
                ls = line.strip().split()
                self.cat[ls[0]] = ls[1]
        self.cat = {k:v for k,v in self.cat.items()}
            
        self.meta = {}
        with open(os.path.join(self.root, 'train_test_split', 'shuffled_train_file_list.json'), 'r') as f:
            train_ids = set([str(d.split('/')[2]) for d in json.load(f)])
        with open(os.path.join(self.root, 'train_test_split', 'shuffled_val_file_list.json'), 'r') as f:
            val_ids = set([str(d.split('/')[2]) for d in json.load(f)])
        with open(os.path.join(self.root, 'train_test_split', 'shuffled_test_file_list.json'), 'r') as f:
            test_ids = set([str(d.split('/')[2]) for d in json.load(f)])
        for item in self.cat:
            self.meta[item] = []
            dir_point = os.path.join(self.root, self.cat[item])
            fns = sorted(os.listdir(dir_point))
            if split=='trainval':
                fns = [fn for fn in fns if ((fn[0:-4] in train_ids) or (fn[0:-4] in val_ids))]
            elif split=='train':
                fns = [fn for fn in fns if fn[0:-4] in train_ids]
            elif split=='val':
                fns = [fn for fn in fns if fn[0:-4] in val_ids]
            elif split=='test':
                fns = [fn for fn in fns if fn[0:-4] in test_ids]
            else:
                print('Unknown split: %s. Exiting..'%(split))
                exit(-1)
                
            for fn in fns:
                token = (os.path.splitext(os.path.basename(fn))[0]) 
                self.meta[item].append(os.path.join(dir_point, token + '.txt'))
        
        self.datapath = []
        for item in self.cat:
            for fn in self.meta[item]:
                self.datapath.append((item, fn))
         
        self.classes = dict(zip(self.cat, range(len(self.cat))))  
        # Mapping from category ('Chair') to a list of int [10,11,12,13] as segmentation labels
        self.seg_classes = {'Earphone': [16, 17, 18], 'Motorbike': [30, 31, 32, 33, 34, 35], 'Rocket': [41, 42, 43], 'Car': [8, 9, 10, 11], 'Laptop': [28, 29], 'Cap': [6, 7], 'Skateboard': [44, 45, 46], 'Mug': [36, 37], 'Guitar': [19, 20, 21], 'Bag': [4, 5], 'Lamp': [24, 25, 26, 27], 'Table': [47, 48, 49], 'Airplane': [0, 1, 2, 3], 'Pistol': [38, 39, 40], 'Chair': [12, 13, 14, 15], 'Knife': [22, 23]}
        
        self.cache = {}
        # self.cache_size = self.__len__()
        preload_file = f"{self.root}/{split}_{self.normalize}_preload.pkl"
        if os.path.exists(preload_file):
            print(f"Preloading all data from {preload_file}")
            with open(preload_file, 'rb') as file:
                self.cache = pickle.load(file)
        else:
            print("Preloading data by reading individual files.")
            self.preload()
            with open(preload_file, 'wb') as file:
                print(f"Saving pre-loaded data at {preload_file}")
                pickle.dump(self.cache, file)


    def __getitem__(self, index):
        point_set, normal, seg, cls = self.cache[index]
        if self.all_points:
            pass
        else:
            choice = np.random.choice(len(seg), self.num_points, replace=True)
            #resample
            point_set = point_set[choice, :]
            seg = seg[choice]
            normal = normal[choice, :]
        if self.transforms is not None:
            point_set = self.transforms(point_set)

        return point_set, torch.from_numpy(normal), torch.from_numpy(seg), torch.from_numpy(cls)
        
    def __len__(self):
        return len(self.datapath)

    def preload(self):
        bar = ProgressBar(max_value=self.__len__())
        for index in range(self.__len__()):
            fn = self.datapath[index]
            cat = self.datapath[index][0]
            cls = self.classes[cat]
            cls = np.array([cls]).astype(np.int64)
            data = np.loadtxt(fn[1]).astype(np.float32)
            point_set = data[:,0:3]
            # https://github.com/charlesq34/pointnet2/blob/master/part_seg/part_dataset_all_normal.py#L95
            normal = data[:, 3:6]
            if self.normalize:
                point_set = pc_normalize(point_set)
            seg = data[:,-1].astype(np.int64)
            self.cache[index] = (point_set, normal, seg, cls)
            bar.update(index)
