from .bases import BaseImageDataset
import os.path as osp
import glob
import re
import os

class Market1501(BaseImageDataset):
    def __init__(self, data_dir = 'data_dir', verbose = True):
        super(Market1501, self).__init__()
        self.dataset_dir = data_dir
        self.train_dir   = osp.join(self.dataset_dir, 'bounding_box_train')
        self.query_dir   = osp.join(self.dataset_dir, 'query')
        self.gallery_dir = osp.join(self.dataset_dir, 'bounding_box_test')

        train   = self._process_dir(self.train_dir, relabel=True)
        query   = self._process_dir(self.query_dir, relabel=False)
        gallery = self._process_dir(self.gallery_dir, relabel=False)

        if verbose:
            print("=> Market1501 loaded")
            self.print_dataset_statistics(train, query, gallery)

        self.train = train
        self.query = query
        self.gallery = gallery

        self.num_train_pids   , self.num_train_imgs   , self.num_train_cams   = self.get_imagedata_info(self.train)
        self.num_query_pids   , self.num_query_imgs   , self.num_query_cams   = self.get_imagedata_info(self.query)
        self.num_gallery_pids , self.num_gallery_imgs , self.num_gallery_cams = self.get_imagedata_info(self.gallery)

    def _process_dir(self, data_dir, relabel=True):
        img_paths = glob.glob(osp.join(data_dir, '*.jpg'))
        pattern   = re.compile(r'([-\d]+)_c(\d)')

        pid_container = set()
        for img_path in img_paths:
            pid, _ = map(int, pattern.search(img_path).groups())
            if pid == -1: continue  # junk images are just ignored
            pid_container.add(pid)
        pid2label = {pid: label for label, pid in enumerate(pid_container)}

        dataset = []
        for img_path in img_paths:
            pid, camid = map(int, pattern.search(img_path).groups())
            if pid == -1: continue  # junk images are just ignored
            #assert 0 <= pid <= 2501  # pid == 0 means background
            assert 1 <= camid <= 6
            camid -= 1  # index starts from 0
            if relabel: pid = pid2label[pid]
            dataset.append((img_path, pid, camid))

        return dataset