from odoo import models, fields, api, _

class PosOrderLine(models.Model):
    _inherit = 'pos.order.line'

    preparation_status = fields.Selection([
        ('waiting', 'Waiting'),
        ('preparing', 'Preparing'),
        ('ready', 'Ready'),
        ('served', 'Served'),
        ('cancelled', 'Cancelled')
    ], string='Preparation Status', default='waiting', tracking=True)

    color = fields.Integer(string='Color', default=0)
    preparation_time_start = fields.Datetime(string='Start Time')
    preparation_time_end = fields.Datetime(string='Ready Time')
    cooking_time = fields.Integer(string='Cooking Time (min)', compute='_compute_cooking_time', store=True)
    
    table_id = fields.Many2one('restaurant.table', related='order_id.table_id', string='Table', store=True)
    floor_id = fields.Many2one('restaurant.floor', related='order_id.table_id.floor_id', string='Floor', store=True)

    @api.depends('preparation_time_start', 'preparation_time_end')
    def _compute_cooking_time(self):
        for line in self:
            if line.preparation_time_start and line.preparation_time_end:
                diff = line.preparation_time_end - line.preparation_time_start
                line.cooking_time = int(diff.total_seconds() / 60)
            else:
                line.cooking_time = 0

    def action_start_preparing(self):
        self.write({
            'preparation_status': 'preparing',
            'preparation_time_start': fields.Datetime.now()
        })

    def action_mark_ready(self):
        self.write({
            'preparation_status': 'ready',
            'preparation_time_end': fields.Datetime.now()
        })

    def action_mark_served(self):
        self.write({
            'preparation_status': 'served'
        })
