# Copyright (C) 2022 Thomas Hoppe (h0bB1T). All rights reserved.
#
# Unauthorized copying of this file via any medium is strictly prohibited.
# Proprietary and confidential.

from typing import Dict, List, Tuple, Union

from ...utils.dev import dmp

class ImageLookup:
    """
    Used to quickly find category and entry using the bin hash.
    """
    def __init__(self):        
        self.__bin_hashes = {} # type: Dict[str, Tuple[str, str]]
        self.__bin_hashes_v2 = {} # type: Dict[str, Tuple[str, str]]


    def add_entry(self, category_key: str, image_key: str, bin_hash: List[str], bin_hash_v2: List[str]):
        """
        Called during repo scan, add entry for fast lookup.
        """
        for hash in bin_hash:
            if hash in self.__bin_hashes:
                c, e = self.__bin_hashes[hash]
                #print(f'Bin hash conflict: {category}/{entry} <-> {c}/{e}')
            self.__bin_hashes[hash] = (category_key, image_key) 

        for hash in bin_hash_v2:
            if hash in self.__bin_hashes_v2:
                c, e = self.__bin_hashes_v2[hash]
                dmp(f'Bin hash v2 conflict: {category_key}/{image_key} <-> {c}/{e}')
            self.__bin_hashes_v2[hash] = (category_key, image_key) 


    def remove_entry(self, bin_hash: str):
        if bin_hash in self.__bin_hashes:
            del self.__bin_hashes[bin_hash]


    def remove_entry_v2(self, bin_hash_v2: str):
        if bin_hash_v2 in self.__bin_hashes_v2:
            del self.__bin_hashes_v2[bin_hash_v2]      


    def get(self, bin_hash: str) -> Tuple[Union[str, None], Union[str, None]]:
        category_key, image_key = self.__bin_hashes.get(bin_hash, (None, None))
        if category_key == None or image_key == None:
            return self.__bin_hashes_v2.get(bin_hash, (None, None))
        else:
            return (category_key, image_key)


    def clear(self):
        self.__bin_hashes.clear()
        self.__bin_hashes_v2.clear()            
