from typing import (
    Dict,
    List,
    Union,
)

from nreports.repository import (
    I18NRepository,
    L10NRepository,
)
from nreports_api.shared import JSON
from ._Line import Line
from .exceptions import (
    InnerListAttributeIsNotAList,
    InnerListMustHaveNameAttr,
)


class InnerListLine(Line):

    def __init__(
        self,
        line: JSON,
    ) -> None:

        super().__init__(line)

        if "name" not in line:
            raise InnerListMustHaveNameAttr()

        if not isinstance(line["innerList"], list):
            raise InnerListAttributeIsNotAList()

        self._inner_list_name = line["name"]
        self._inner_list: List[Line] = []

        for text in line["innerList"]:
            self._inner_list.append(Line.build(line=text))

    def inner_format(
        self,
        data: Dict[str, JSON],
        i18n_repository: I18NRepository,
        l10n_repository: L10NRepository,
    ) -> List[Dict[str, Union[str, Dict[str, str]]]]:

        formatted = []
        for sub_group_data in data[self._inner_list_name]:
            for line in self._inner_list:
                formatted_line = line.format(
                    data=sub_group_data,
                    i18n_repository=i18n_repository,
                    l10n_repository=l10n_repository,
                )
                formatted.extend(formatted_line)

        return formatted

    def get_inner_data_to_build(
        self,
    ) -> Dict[str, JSON]:

        ret: Dict[str, JSON] = {
            "template": {},
            self._inner_list_name: []
        }
        for line in self._inner_list:
            ret["template"].update(line.get_inner_data_to_build())

        return ret

    def set_inner_list(
        self,
        inner_list: List[Line],
    ) -> None:

        self._inner_list = inner_list
