from .models import GtinProduct
from django.db.models import ObjectDoesNotExist
import requests
import logging

LOGGER = logging.getLogger(__name__)


def ask_upcitemdb_service(gtin):
    request = f'https://api.upcitemdb.com/prod/trial/lookup?upc={gtin}'
    response = requests.get(request)
    if response.status_code == 200:
        productJson = response.json()
        print(f"Got {productJson['total']} result records")
        if productJson['total'] > 0:
            product = GtinProduct.objects.create(gtin=gtin, api_request=request, api_response=productJson)
            if 'title' in productJson['items'][0]:
                product.name = productJson['items'][0]['title']
            if 'brand' in productJson['items'][0]:
                product.brand = productJson['items'][0]['brand']
            LOGGER.debug(
                f"Creating new product entry for gtin={gtin}:\nrequest={request}\nresponse={response.status_code}:{productJson}")
            product.save()
            return product
    return None

def ask_digiteyes_service(gtin):
    request = f'https://www.digit-eyes.com/gtin/v2_0/?upcCode={gtin}&field_names=all&language=en&app_key=%s&signature=%s'
    response = requests.get(request)
    if response.status_code == 200:
        product_json = response.json()
        print(f"Got {product_json['description']}")
        if product_json['return_code'] == '0':
            product = GtinProduct.objects.create(gtin=gtin, api_request=request, api_response=product_json)
            if 'description' in product_json:
                product.name = product_json['description']
            if 'brand' in product_json:
                product.brand = product_json['brand']
            LOGGER.debug(
                f"Creating new product entry for gtin={gtin}:\nrequest={request}\nresponse={response.status_code}:{product_json}")
            product.save()
            return product
    return None

def ask_opengtindb_service(gtin):
    request = f'http://opengtindb.org/?ean={gtin}&cmd=query&queryid=400000000'
    response = requests.get(request)
    if response.status_code == 200:
        product_txt = response.text
        print(f"Got {product_txt}")
        if product_txt.startswith('error=0'):
            product = GtinProduct.objects.create(gtin=gtin, api_request=request, api_response=product_txt)
            product_props = product_txt.splitlines()
            for prop in product_props:
                if prop.startswith('name='):
                    product.name = prop[5:]
                if prop.startswith('vendor='):
                    product.brand = prop[7:]
            LOGGER.debug(
                f"Creating new product entry for gtin={gtin}:\nrequest={request}\nresponse={response.status_code}:{product_txt}")
            product.save()
            return product
    return None


def ask_remote_services(gtin):
    product = ask_upcitemdb_service(gtin)
    if product is not None:
        return product
    product = ask_digiteyes_service(gtin)
    if product is not None:
        return product
    product = ask_opengtindb_service(gtin)
    if product is not None:
        return product
    return None


def get_by_gtin(gtin):
    try:
        product = GtinProduct.objects.get(gtin=gtin)
    except ObjectDoesNotExist:
        # ask remote services
        product = ask_remote_services(gtin)
    return product
