from datetime import datetime
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError


class MskService(models.Model):
    _name = "msk.service"
    _description = _("Msk Service")
    _rec_name = "service_id"

    opening_time = fields.Char(string=_("Start time"), required=True)
    opening_times = fields.Datetime(string=_("Start time"), required=True)
    closing_time = fields.Char(string=_("End time"), required=True)
    is_active = fields.Boolean(string=_("Is Active"), default=True,
                                help=_("If this service is not working, uncheck this field"))
    description = fields.Text(string=_("Description"), required=True)
    price_for_call = fields.Float(string=_("Price for call"), required=True)
    discount = fields.Float(string=_("Discount"), defgault=0)
    cancellation_time = fields.Integer(string=_("Cancellation Time in Minutes"), required=True)
    msk_id = fields.Many2one("res.users", string=_("MSK"), required=True)
    service_id = fields.Many2one("service", string=_("Service"), required=True)
    mahalla_id = fields.Many2one("mahalla", string=_("Mahalla"))
    employee_ids = fields.Many2many(
        "employee",
        "msk_service_employee_rel",
        "msk_service_id",
        "employee_id",
        string=_("Employees")
    )
    image = fields.Binary(string=_('Image'))

    # Define a unique constraint
    _sql_constraints = [
        (
            "msk_service_unique",
            "unique(msk_id, service_id)",
            "The combination of MSK and Service must be unique.",
        )
    ]

    @api.constrains("msk_id", "service_id")
    def _check_unique_msk_service(self):
        for record in self:
            duplicate = self.search_count(
                [
                    ("msk_id", "=", record.msk_id.id),
                    ("service_id", "=", record.service_id.id),
                    ("id", "!=", record.id),  # Exclude the current record
                ]
            )
            if duplicate:
                raise ValidationError(
                    "The combination of MSK and Service must be unique."
                )

    @api.constrains("opening_time", "closing_time")
    def _check_opening_closing_time(self):
        time_format = "%H:%M"  # 24-hour format: 'HH:MM'
        for record in self:
            try:
                opening_time_obj = datetime.strptime(record.opening_time, time_format)
                closing_time_obj = datetime.strptime(record.closing_time, time_format)

                # Ensure opening time is before closing time
                if opening_time_obj >= closing_time_obj:
                    raise ValidationError("Opening time must be before closing time.")

            except ValueError:
                raise ValidationError("Time must be in the format HH:MM (24-hour).")

            # Ensure times are within the 24-hour range
            if not (record.opening_time >= "00:00" and record.closing_time <= "23:59"):
                raise ValidationError("Time must be within the range 00:00 to 23:59.")

    @api.model
    def create(self, vals):
        # Set default msk_id to current user if not provided
        if 'msk_id' not in vals:
            vals['msk_id'] = self.env.user.id
        return super(MskService, self).create(vals) add daterange to discount, and set it to 0 when time arrives, and add validations