from datetime import date
from typing import (
    Optional,
    Type,
)
try:
    from xml.etree.cElementTree import Element
except ImportError:
    from xml.etree.ElementTree import Element


from ._PosStateValue import PosStateValue


class PosState(object):
    def __init__(
        self,
        state,                  # type: PosStateValue
        business_period,        # type: Optional[date]
    ):
        self.state = state
        self.business_period = business_period

    @classmethod
    def from_xml(
        cls,        # type: Type[PosState]
        xml,        # type: Element
    ):

        period_str = xml.attrib["period"]

        business_period = None
        if period_str != "0":
            year = period_str[0:4]
            month = period_str[4:6]
            day = period_str[6:8]
            business_period = date(
                year=int(year),
                month=int(month),
                day=int(day),
            )

        return cls(
            state=PosStateValue(int(xml.attrib["stateCode"])),
            business_period=business_period,
        )
