import json
from xml.etree import cElementTree as eTree

from ._Type import JSON

class PosModelFormatter:

    def __init__(self):
        return

    def get_pos_model_dict(
        self,       # type: PosModelFormatter
        pos_model,  # type: eTree.Element
    ):
        # type: (...) -> JSON

        pos_state = pos_model.find("PosState")
        language = pos_model.find("Language")
        operator = pos_model.find("Operator")
        current_order = pos_model.find("CurrentOrder")
        working_mode = pos_model.find("WorkingMode")
        used_service = pos_model.find("UsedServices")
        stored_modified = pos_model.find("STORE_MODIFIED")
        pos_model_dict = {
            "posId": pos_model.attrib.get("posId"),
            "posState": self._get_attribs(pos_state),
            "language": self._get_attribs(language),
            "operator": self._get_attribs(operator),
            "cashDrawerStatus": self._get_text(pos_model, "CashDrawerStatus"),
            "currentOrder": self._get_attribs(current_order),
            "customs": self._group_same_tag("Custom", pos_model),
            "workingMode": self._get_attribs(working_mode),
            "usedServices": self._group_same_tag("Service", used_service),
        }

        if stored_modified:
            tables = stored_modified.find("Tables")
            pos_model_dict["tables"] = self._group_same_tag("Table", tables)

        return pos_model_dict

    @staticmethod
    def _get_text(
        element,  # type: eTree.Element
        tag,      # type: str
    ):
        # type: (...) -> str

        if element is None:
            return ""

        found = element.find(tag)
        if not found:
            return ""

        return found.text.strip()

    @staticmethod
    def _get_attribs(
        element,  # type: eTree.Element
    ):
        # type: (...) -> JSON

        if element is None:
            return {}

        result = {}
        for key, value in element.attrib.items():
            try:
                result[key] = json.loads(value)

            except (Exception,):
                result[key] = value

        return result

    @staticmethod
    def _group_same_tag(
        tag,        # type: str
        element,    # type: eTree.Element
    ):
        # type: (...) -> JSON

        if element is None:
            return []

        group = []
        for custom_elem in element.findall(tag):
            attrs = PosModelFormatter._get_attribs(custom_elem)
            group.append(attrs)

        return group
