from datetime import datetime
from typing import (
    List,
    Optional,
)
from xml.etree.ElementTree import Element

from ._CustomProperty import CustomProperty
from ._OrderState import OrderState
from ._SaleLine import SaleLine
from ._StateHistory import StateHistory
from ._Tender import Tender


class Order(object):
    def __init__(
        self,                       # type: Order
        order_id,                   # type: int
        state_history,              # type: List[StateHistory]
        total_amount=None,          # type: Optional[float]
        total_gross=None,           # type: Optional[float]
        discount_amount=None,       # type: Optional[float]
        total_tender=None,          # type: Optional[float]
        total_after_discount=None,  # type: Optional[float]
        due_amount=None,            # type: Optional[float]
        change=None,                # type: Optional[float]
        tip=None,                   # type: Optional[float]
        sale_lines=None,            # type: Optional[List[SaleLine]]
        custom_properties=None,     # type: Optional[List[CustomProperty]]
        tenders=None,               # type: Optional[List[Tender]]
        order_xml=None,             # type: Element
    ):
        # type: (...) -> None

        self.order_id = order_id
        self.state_history = state_history
        self.total_amount = total_amount
        self.total_gross = total_gross
        self.discount_amount = discount_amount
        self.total_tender = total_tender
        self.total_after_discount = total_after_discount
        self.due_amount = due_amount
        self.change = change
        self.tip = tip
        self.total_gross = total_gross
        self.sale_lines = sale_lines or []
        self.custom_properties = custom_properties or []
        self.tenders = tenders or []
        self.order_xml = order_xml

    def get_custom_property(
        self,   # type: Order
        key,    # type: str
    ):
        # type: (...) -> Optional[CustomProperty]

        for custom_property in self.custom_properties:
            if custom_property.key == key:
                return custom_property

        return None

    @property
    def state(self):
        # type: (...) -> OrderState
        return self.state_history[-1].state

    @property
    def created_at(self):
        # type: (...) -> datetime
        return self.state_history[0].created_at

    def to_xml(self):
        # type: (...) -> Element
        return self.order_xml
