from odoo import models, fields, api, _
from odoo.exceptions import UserError
from odoo.tools import html_escape
from markupsafe import Markup, escape

class LoanItem(models.Model):
    _name = "loan.deposit.item"
    _description = "Loan Deposit Items"
    _inherit = ['mail.thread']  
    _rec_name = "loan_id"

    loan_id = fields.Many2one("loan.management", string="Loan")
    item_name = fields.Char("Item Name", required=True, tracking=True)
    date = fields.Date("Date", required=True, tracking=True)
    type = fields.Selection([
        ('gold', 'Gold'),
        ('silver', 'Silver'),
        ('mix', 'Gold + Silver (Mix)'),
    ], string="Type", required=True, tracking=True)

    weight = fields.Float("Weight (Gram)", tracking=True)
    photo = fields.Binary("Photo")
    is_returned = fields.Boolean(
        string="Returned",
        default=False,
        tracking=True
    )

    returned_date = fields.Date(
        string="Returned Date",
        readonly=True
    )

    returned_by = fields.Many2one(
        'res.users',
        string="Returned By",
        readonly=True
    )

    def action_return_item(self):
        for item in self:
            if item.is_returned:
                raise UserError(_("This item is already returned."))

            item.write({
                'is_returned': True,
                'returned_date': fields.Date.today(),
                'returned_by': self.env.user.id,
            })

            # Chatter entry on LOAN
            if item.loan_id:
                item.loan_id.message_post(
                    body=Markup(
                        "<p>Deposit item <b>%s</b> (%s) has been returned.</p>"
                        "<p><b>Returned by:</b> %s</p>"
                    ) % (
                        item.item_name,
                        item.type,
                        self.env.user.name,
                    ),
                    subtype_xmlid="mail.mt_note",
                )
