"""
Index images on a tensor database
"""
import concurrent.futures

from loader.reader import Importer
from tensors.tensor_database import TensorDatabase
from features.extractors import FeatureExtractor
from features.extractors import Features

class Indexer:
    """
    Indexer of images
    """
    def __init__(self, images_path, database_path):
        self._images_path = images_path
        self._database_path = database_path

    @staticmethod
    def name_normalize(name):
        return name.replace('/', '|')

    @staticmethod
    def name_denormalize(name):
        return name.replace('|', '/')

    def index(self):
        """
        Do the index process
        """
        importer = Importer(self._images_path)
        tensors = TensorDatabase(self._database_path)
        extract = Features(FeatureExtractor.SIFT)

        with concurrent.futures.ThreadPoolExecutor() as executor:
            futures = {
                executor.submit(
                    tensors.add,
                    self.name_normalize(name),
                    extract.descriptors(image)
                ): name
                for name, image in importer.load()
            }

            for future in concurrent.futures.as_completed(futures):
                result = future.result()
