from .autoadder import autoadder
from .app_route import app_route
from .exception import autoadder_exception
from .exception import incomplete_request_exception
from .exception import access_denied_exception
from .users_collection import users_collection

class autoadder_app(app_route):
    def __init__(
        self, 
        users: users_collection, 
        target: autoadder | None
    ) -> None:
        super().__init__()

        self.__users = users
        self.__worker = target

    def __login(self, params: dict) -> None:
        if not "apikey" in params:
            raise incomplete_request_exception("apikey")

        if self.__users.get(params["apikey"]) is None:
            raise access_denied_exception()

    @property 
    def worker(self) -> autoadder:
        if self.__worker is None:
            raise autoadder_exception("Google Clous API key and CS not set.")
        
        return self.__worker

    def find(self, params: dict) -> dict:
        try:
            self.__login

            if not "barcode" in params:
                raise incomplete_request_exception("barcode")

            result = self.worker.find(params["barcode"])
            return self._success(found = result)

        except Exception as error:
            return self._fail(str(error))
