import json
import googlesearch
import google_images_search

from .validator import barcode_validator
from .exception import bad_request_exception
from .exception import autoadder_exception

class autoadder:
    def __init__(self, apikey: str, engine: str) -> None:
        self.__apikey = apikey
        self.__engine = engine

    def __images(self) -> object:
        return google_images_search.GoogleImagesSearch(
            self.__apikey,
            self.__engine
        )

    def __search(self, phrase: str) -> object:
        for count in googlesearch.search(phrase, advanced= True):
            return count

    def __check_barcode(self, barcode: str) -> None:
        if barcode_validator(barcode).invalid:
            raise bad_request_exception("Invalid barcode")

    def find(self, barcode: str) -> dict:
        self.__check_barcode(barcode)

        title = self.__search(barcode).title
        description = title
        author = "Somebody"

        try:
            image_search = self.__images()
            image_search.search(search_params = {
                "q": barcode,
                "num": 1,
                "filetype": "jpg"
            })

            images = image_search.results()
        except Exception as error:
            raise autoadder_exception("Google API not work. Check API key.")

        if len(images) < 1:
            image = ""
        else:
            image = images[0].url

        return {
            "title": title,
            "description": description,
            "author": author,
            "barcode": barcode,
            "image": image
        }
