import json
from typing import Dict

from nreports.interactor.build_report import BuildReportInteractor
from nreports.interactor.build_report.dto import BuildReportRequest
from nreports_api.shared.report_dto import ReportDto
from ._BaseNReportProcessor import BaseNReportProcessor


class BuildReportProcessor(BaseNReportProcessor):

    def __init__(
        self,
        interactor: BuildReportInteractor,
    ) -> None:
        super().__init__()

        self.interactor = interactor

    def parse_data(
        self,
        data: bytes,
    ) -> BuildReportRequest:

        try:
            data_dict = json.loads(s=data.decode())
        except Exception:
            raise self.InvalidJson()

        report_name = self._parse_report_name(data_dict=data_dict)

        return BuildReportRequest(
            pos_id=data_dict["posId"],
            report_name=report_name,
            data=data_dict,
        )

    def call_business(
        self,
        request: BuildReportRequest,
    ) -> ReportDto:

        return self.interactor.execute(request=request)

    def _parse_report_name(
        self,
        data_dict: Dict,
    ) -> str:

        report_name = None
        try:
            report_name = str(data_dict["reportName"].strip())
        finally:
            if not report_name:
                raise self.MissingReportName()

        return report_name
