from odoo import models, fields, api
from odoo.exceptions import UserError, ValidationError,Warning
from datetime import date,datetime,timedelta

class booking_room(models.Model):
    _name = 'booking.room'
    _description = 'booking room'

    name2 = fields.Char('name',required=True)
    name=fields.Char('room name',compute='_compute_room_name')
    description = fields.Text('description')
    capacity = fields.Integer('max capacity')
    available_seats = fields.Integer('available seats', compute='_compute_available_seats')
    location_id=fields.Many2one('booking.location', string='location')
    
    def _compute_available_seats(self):
        for reg in self:
            today=date.today()
            events=self.env['event.event'].search([('booking_event','=',True),('date_end','>=',today)])
            count_room_seats=0
            if events:
                for event in events:
                    count_room_seats=count_room_seats+self.env['event.registration'].search_count([('event_id','=',int(event.id)),('room_id','=',int(reg.id))])
            reg.available_seats=count_room_seats
                
    def _compute_room_name(self):
        for rec in self:
             rec.name=''
             if rec.name2:
                rec.name=rec.name2+'('+str(rec.available_seats)+'/'+str(rec.capacity)+')'
                
             
class booking_room_occupation(models.Model):
    _name = 'booking.room.occupation'
    _description = 'room occupation'

    room_id = fields.Many2one('booking.room', string='room')
    event_id=fields.Many2one('event.event',domain="[('date_begin','>=',context_today().strftime('%Y-%m-%d 00:00:00'))]")
    event_registration_id = fields.Many2one('event.registration', string='event registration',domain="['&',('event_id', '=', event_id),('room_id', '=', False),('event_id.booking_event', '=', True)]")
    name=fields.Char(related='event_registration_id.name')
    
    date_begin=fields.Datetime(related='event_registration_id.event_id.date_begin')
    date_end=fields.Datetime(related='event_registration_id.event_id.date_begin')

    @api.model
    def create(self,vals):

        res=super(booking_room_occupation, self).create(vals)
        
        #event_reg=self.env['booking.room.occupation'].search([])
        
        event_reg=self.env['event.registration'].search([('id','=',int(res.event_registration_id))])
       
        
        event_reg.room_id= res.room_id
        return res