from django.utils.translation import gettext_lazy as _

from oscar.core.loading import get_class, get_model

ReportGenerator = get_class("dashboard.reports.reports", "ReportGenerator")
ReportCSVFormatter = get_class("dashboard.reports.reports", "ReportCSVFormatter")
ReportHTMLFormatter = get_class("dashboard.reports.reports", "ReportHTMLFormatter")

StockAlert = get_model("partner", "StockAlert")


class StockAlertReportCSVFormatter(ReportCSVFormatter):
    filename_template = "stock_alerts.csv"

    def generate_csv(self, response, stockalerts):
        writer = self.get_csv_writer(response)
        header_row = [
            _("Product"),
            _("Partner"),
            _("Low stock threshold"),
            _("Current available stock"),
            _("Date alert raised"),
        ]
        writer.writerow(header_row)

        for alert in stockalerts:
            row = [
                alert.stockrecord.product.get_title(),
                alert.stockrecord.partner.display_name,
                alert.stockrecord.low_stock_threshold,
                alert.stockrecord.net_stock_level,
                alert.date_created,
            ]
            writer.writerow(row)


class StockAlertReportHTMLFormatter(ReportHTMLFormatter):
    filename_template = "dashboard/reports/partials/stockalerts_report.html"


class StockAlertReportGenerator(ReportGenerator):
    code = "stock_alerts"
    description = _("Open stock alerts")
    date_range_field_name = "date_created"

    formatters = {
        "CSV_formatter": StockAlertReportCSVFormatter,
        "HTML_formatter": StockAlertReportHTMLFormatter,
    }

    def generate(self):
        # Only open stock alerts are usefull, as closed ones are already handled.
        stock_alerts = self.get_queryset()
        return self.formatter.generate_response(stock_alerts)

    def get_queryset(self):
        return StockAlert.objects.filter(status=StockAlert.OPEN)
