import json
from json import dumps
from xml.etree.ElementTree import Element

from typing import Optional, Dict

from ._ServicePeriod import ServicePeriod


class SaleLine(object):
    def __init__(self, obj):
        # type: (Element) -> None

        self.qty = float(obj.get("multipliedQty") or 0)
        self.context = obj.get("itemId")
        self.item_id = obj.get("partCode")
        self.price_key = int(obj.get("priceKey")) if obj.get("priceKey") else None
        self.item_price = float(obj.get("itemPrice") or 0)
        unit_price = float(obj.get("overwrittenUnitPrice", obj.get("unitPrice") or 0))
        self.unit_price = float(obj.get("addedUnitPrice") or 0) if unit_price == 0 else unit_price
        self.unit_discount = float(obj.get("itemDiscount") or 0) / (self.qty or 1)
        self.current_unit_price = self.unit_price - self.unit_discount
        self.level = obj.get("level")
        self.line_number = obj.get("lineNumber")
        self.key = "{}.{}.{}.{}".format(self.line_number, self.level, self.context, self.item_id)
        self.product_name = obj.get("productName") or ""
        self.item_type = obj.get("itemType")

        self._get_custom_properties_info(obj)

    def _get_custom_properties_info(self, obj):
        self.seat = None
        self.service_period = None
        self.sale_type = None
        self.brand = None
        custom_properties = self.get_custom_properties(obj)
        if custom_properties:
            self.seat = custom_properties.get("seat")
            self.service_period = ServicePeriod(custom_properties.get("servicePeriod"))
            self.sale_type = custom_properties.get("saleType")
            self.brand = custom_properties.get("brand")

    @staticmethod
    def get_custom_properties(obj):
        # type: (Element) -> Optional[Dict]

        try:
            custom_properties_json = obj.get("customProperties")
            if not custom_properties_json:
                return None

            custom_properties = json.loads(custom_properties_json)
            return custom_properties
        except Exception as _:
            return None

    def to_json(self):
        return dumps(self, default=lambda o: o.__dict__ if hasattr(o, '__dict__') else str(o), sort_keys=True)
