# -*- coding: utf-8 -*-
from odoo import api, fields, models, exceptions
from odoo.tools import float_utils as floatTool

class EstatePropertyOffer(models.Model):

    # ------------- Private attributes ------------------------- #

    _name = "estate.property.offer"
    _description = "Offers made on properties"
    _order = "price desc"

    _sql_constraints = [
        ('check_price', 'CHECK (price > 0)', 'Expected price should be superior to 0'),
    ]

    # ------------- Fields ------------------------- #

    price = fields.Float()
    state = fields.Selection(copy=False, selection=[('accepted', 'Accepted'), ('refused', 'Refused')])
    partner_id = fields.Many2one("res.partner", required=True)
    property_id = fields.Many2one("estate.property", required=True)
    validity = fields.Integer(default=7, string='validity (days)')
    date_deadline = fields.Date(compute="_compute_date_deadline", inverse="_inverse_date_deadline")
    property_type_id = fields.Many2one(related="property_id.property_type_id", store="True")

    # ---------------- CRUD Methods ------------------------- #

    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            if self.env['estate.property'].browse(vals['property_id']).state == 'new':
                self.env['estate.property'].browse(vals['property_id']).write({'state': 'offer_received'})
        return super().create(vals_list)
    
    # ------------- Compute methods  ------------------------- #

    @api.depends('validity', 'create_date')
    def _compute_date_deadline(self):
        for record in self:
            record.date_deadline = fields.Date.add(record.create_date or fields.Date.today(), days=record.validity)
    
    def _inverse_date_deadline(self):
        for record in self:
            record.validity = (record.date_deadline - (record.create_date.date() or fields.Date.today())).days

    # ------------- Actions ------------------------- #

    def action_accept(self):
        if self.exists():
            if "accepted" in self.mapped("property_id.offer_ids.state"):
                raise exceptions.UserError("An offer as already been accepted.")
            self.write(
                {
                    "state": "accepted",
                }
            )
            return self.mapped("property_id").write(
                {
                    "state": "offer_accepted",
                    "selling_price": self.price,
                    "buyer_id": self.partner_id.id,
                    "salesman_id": self.create_uid.id
                }
            )
        else:
            raise exceptions.MissingError('Offer not found')

    def action_reject(self):
        if self.exists():
            if self.state == 'accepted':
                raise exceptions.UserError('Cannot accept an offer refused')
                return False
            else:
                self.state = 'refused'
            return True
        else:
            raise exceptions.MissingError('Offer not found')
            return False