from odoo import api, fields, models, _


class ServicesReportsWizard(models.TransientModel):
    _name = "fleet.services.report.wizard"
    _description = "Fleet Services Report"

    service_id = fields.Many2one("fleet.service.type", "Service", index=True)
    vehicle_id = fields.Many2one("fleet.vehicle", "Vehicle", index=True)
    date_from = fields.Date(
        string="From", required=True, default=fields.Date.context_today
    )
    date_to = fields.Date(string="To", required=True, default=fields.Date.context_today)

    @api.onchange("date_from")
    def _onchange_date_from(self):
        """
        set valid date_from on changing it
        """
        if not self.date_to:
            if self.date_from and self.date_from > fields.Date.context_today(self):
                self.date_from = fields.Date.context_today(self)
        else:
            if self.date_from and self.date_from > self.date_to:
                self.date_from = self.date_to

    @api.onchange("date_to")
    def _onchange_date_to(self):
        """
        set valid date_to on changing it
        """
        if self.date_from and self.date_to and self.date_from > self.date_to:
            self.date_to = self.date_from
        if self.date_to and self.date_to > fields.Date.context_today(self):
            self.date_to = fields.Date.context_today(self)

    def action_print_report(self):
        report_filters = {
            "service_id": self.service_id.id,
            "vehicle_id": self.vehicle_id.id,
            "date_from": self.date_from,
            "date_to": self.date_to,
        }

        return self.env.ref(
            "fleet_advanced_reports.action_report_fleet_services"
        ).report_action(self, data=report_filters)
