# Copyright 2020 Carlos Roca <carlos.roca@tecnativa.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
import barcode  # pylint: disable=missing-manifest-dependency
from barcode.writer import SVGWriter  # pylint: disable=missing-manifest-dependency

from odoo import http
from odoo.http import request

from odoo.addons.web.controllers.report import ReportController


class ReportController(ReportController):
    @http.route()
    def report_barcode(
        self,
        barcode_type,
        value,
        width=600,
        height=100,
        humanreadable=0,
        quiet=1,
    ):
        if barcode_type == "gs1_128":
            Gs1_128 = barcode.get_barcode_class("gs1_128")
            writer = SVGWitoutTextWriter(module_max_height=height)
            gs1_128 = Gs1_128(str(value), writer=writer)
            image = gs1_128.render(
                writer_options={"module_width": 0.5, "quiet_zone": 0.5}
            )
            return request.make_response(
                image, headers=[("Content-Type", "image/svg+xml")]
            )
        return super().report_barcode(
            barcode_type,
            value,
            width=width,
            height=height,
            humanreadable=humanreadable,
            quiet=quiet,
        )


class SVGWitoutTextWriter(SVGWriter):
    """This class extend the SVGWriter of python-barcode to delete the text on
    the barcode image generated by this addon."""

    module_max_height: int

    def __init__(self, module_max_height=100) -> None:
        super().__init__()
        self.module_max_height = module_max_height

    def _create_module(self, xpos, ypos, width, color):
        # Background rect has been provided already, so skipping "spaces"
        if color != self.background:
            element = self._document.createElement("rect")
            attributes = {
                "x": "{:.3f}mm".format(xpos),
                "y": "{:.3f}mm".format(ypos),
                "width": "{:.3f}mm".format(width),
                "height": str(self.module_max_height),
                "style": f"fill:{color}",
            }
            for key, value in attributes.items():
                element.setAttribute(key, value)
            self._group.appendChild(element)

    def _create_text(self, xpos, ypos):
        pass
