import base64
import json
from xml.etree import cElementTree as eTree

from typing import Dict, Any, List

from nreports_api.shared import JSON
from .._DataBuilder import DataBuilder


class KitchenLabelBuilder(DataBuilder):

    def build_data(
        self,
        data_to_build: Dict[str, JSON],
        **kwargs: Any,
    ) -> Dict[str, JSON]:

        production_order = eTree.XML(base64.b64decode(kwargs["productionOrder"] + '===='))
        order_id = production_order.get("order_id")
        items = production_order.findall(".//Item")

        data_by_labels = []
        for item in items:
            item_data_labels = self._get_labels_from_item(item)
            data_by_labels.extend(item_data_labels)

        total_labels = len(data_by_labels)
        for index, label in enumerate(data_by_labels):
            label["CURRENT_LABEL"] = index + 1
            label["TOTAL_LABELS"] = total_labels
            label["ORDER_ID"] = order_id

        data_to_build["labels"] = data_by_labels
        return data_to_build

    @staticmethod
    def _get_labels_from_item(
        item: eTree.Element
    ) -> List[JSON]:

        label_tag = item.find("./CustomParams/CustomParam[@id='KitchenLabels']")
        if label_tag is None:
            return []

        item_comment = item.find("Comment").get("comment") if item.find("Comment") is not None else ""
        item_labels = json.loads(label_tag.get("value"))

        data_by_labels = []
        initial_index = len(data_by_labels)
        for index, label in enumerate(item_labels, start=initial_index):
            item_comment = item_comment if label.get("observation", False) is True else ""
            label_data = {"LABEL_TEXT": label.get("text", ""), "OBSERVATION": item_comment}

            data_by_labels.append(label_data)

        return data_by_labels
