import json

from ._Line import Line
from ._LineParser import JSON


class JSONReportParserToHtml(object):

    def parse(
        self,      # type: JSONReportParserToHtml
        report,    # type: str
    ):
        # type: (...) -> str

        html = []
        report = json.loads(report)
        if not report:
            return ""

        columns = 38
        header = report[0].get("header")
        if header is not None:
            columns = header.get("columns", 38)
            report.pop(0)

        self._add_break_line_at_start_and_end(report=report)
        for report_line in report:
            html_line = Line.parse(
                line=report_line,
                columns=columns,
            )
            html.extend(html_line)
            html.append("<br/>")

        return "".join(html)

    @staticmethod
    def _add_break_line_at_start_and_end(
        report,    # type: JSON
    ):
        # type: (...) -> None

        break_line = {
            "command": "{CMD_BREAK_LINE}"
        }
        report.insert(
            0,
            break_line,
        )
        report.extend([
            break_line,
            break_line,
        ])
