import json
from django.utils.safestring import mark_safe

from ocyan.main.encoding import OcyanJSONEncoder


def safe_json_dumps(data, encoder=OcyanJSONEncoder):
    return mark_safe(json.dumps(data, cls=encoder))


def parse_product(product):
    categories = product.get_categories()

    if categories.exists():
        categorie_name = categories.first().name
        categorie_name2 = categories.last().name
    else:
        categorie_name = categorie_name2 = "-"

    stockrecord = product.stockrecords.first()
    if stockrecord and stockrecord.price_incl_tax is not None:
        price = float(stockrecord.price_incl_tax)
    else:
        price = None

    brand = getattr(product.attr, "brand", "-")

    return dict(
        item_id=product.upc,
        item_name=product.get_title(),
        item_brand=brand,
        item_category=categorie_name,
        item_category2=categorie_name2,
        price=price,
        quantity=1,
    )


def parse_line(line):
    product = parse_product(line.product)

    product.update(
        dict(
            price=float(line.line_price_incl_tax),
            quantity=line.quantity,
        )
    )

    return product
