"""
Utils for the google_shopping and google_rich_snippets plugin.
"""

import logging

from stdnum import ean, isbn

from .runtime import get_config

gtin_attr_code = get_config("google", "gtin_attribute", "barcode")
brand_attr_code = get_config("google", "brand_attribute", "brand")
mpn_attr_code = get_config("google", "mpn_attribute", "mpn")
product_type_attr = get_config("google", "product_type_attribute")
color_attr_code = get_config("google", "color_attribute", "color")

logger = logging.getLogger(__name__)


def get_gtin(instance):
    try:
        barcode = getattr(instance.attr, gtin_attr_code)
        if ean.is_valid(barcode):
            return barcode
        elif isbn.is_valid(barcode):
            return barcode
    except AttributeError:
        barcode = instance.upc
        if ean.is_valid(barcode):
            return barcode
        elif isbn.is_valid(barcode):
            return barcode
    except Exception as e:  # pylint: disable=broad-except
        logger.exception(e)

    return None


def get_mpn(instance):
    return getattr(instance.attr, mpn_attr_code, None)


def get_brand(instance):
    return getattr(instance.attr, brand_attr_code, None)


def get_product_type(product):
    if product_type_attr is None:
        return product.get_product_class().name
    else:
        return getattr(
            product.attr, product_type_attr, product.get_product_class().name
        )


def get_color(instance):
    return getattr(instance.attr, color_attr_code, None)
