# This file is part of Presik.  The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
from trytond.pyson import Eval
from trytond.model import Workflow, ModelView, ModelSQL, fields, Unique
from trytond.pool import Pool

STATES = {'invisible': (Eval('type') != 'service')}


class RoomCleaningType(ModelSQL, ModelView):
    "Room Cleaning Type"
    __name__ = "hotel.housekeeping.cleaning_type"
    name = fields.Char('Name', required=True)
    description = fields.Text('Description')
    kind = fields.Selection([
        ('tweak', 'Tweak'),
        ('deep', 'Deep'),
        ('standard', 'Standard'),
        ], 'Kind', required=True)


class Housekeeping(Workflow, ModelSQL, ModelView):
    'HouseKeeping'
    __name__ = 'hotel.housekeeping'
    employee = fields.Many2One('company.employee', 'Employee')
    room = fields.Many2One('hotel.room', 'Room', required=True)
    state = fields.Selection([
        ('inspected', 'Inspected'),
        ('dirty', 'Dirty'),
        ('clean', 'Clean'),
        ('maintenance', 'Maintenance'),
        ], 'Status', required=True, readonly=True)
    state_string = state.translated('state')
    availability = fields.Selection([
        ('blocked', 'Blocked'),
        ('available', 'Available'),
        ('occupied', 'Occupied'),
        ], 'Availability', required=True)
    cleaning_type = fields.Many2One('hotel.housekeeping.cleaning_type',
        'Cleaning Type', required=False)
    availability_string = state.translated('availability')
    check_list = fields.Text('Check List')
    tasks = fields.One2Many('hotel.housekeeping.task', 'housekeeping',
        'House Tasks')
    start_date_assigned = fields.Date('Start Date Assigned')
    end_date_assigned = fields.Date('End Date Assigned')
    notes = fields.Text('Notes')
    check_in_time = fields.Function(fields.Time('Check In Time'),
        'get_check_in_time')
    check_out_time = fields.Function(fields.Time('Check In Time'),
        'get_check_out_time')
    amenities = fields.Function(fields.Many2Many('hotel.room-hotel.amenities',
        'room', 'amenities', 'Amenities'), 'get_amenities')

    @classmethod
    def __setup__(cls):
        super(Housekeeping, cls).__setup__()
        t = cls.__table__()
        cls._sql_constraints += [
            ('room_uniq', Unique(t, t.room), 'The room must be unique.'),
        ]
        cls._transitions |= set((
            ('clean', 'dirty'),
            ('clean', 'inspected'),
            ('clean', 'maintenance'),
            ('dirty', 'clean'),
            ('dirty', 'maintenance'),
            ('dirty', 'inspected'),
            ('maintenance', 'inspected'),
            ('maintenance', 'dirty'),
            ('inspected', 'dirty'),
            ('inspected', 'maintenance'),
            ('inspected', 'clean'),
        ))
        cls._buttons.update({
            'clean': {
                'invisible': Eval('state').in_(['maintenance', 'clean']),
            },
            'dirty': {
                'invisible': Eval('state').in_(['dirty']),
            },
            'inspected': {
                'invisible': Eval('state').in_(['inspected']),
            },
            'maintenance': {
                'invisible': Eval('state').in_(['maintenance']),
            },
        })

    @staticmethod
    def default_state():
        return 'clean'

    @staticmethod
    def default_avaibility():
        return 'available'

    @classmethod
    @ModelView.button
    @Workflow.transition('clean')
    def clean(cls, records):
        for rec in records:
            rec.cleaning_type = None
            rec.save()

    @classmethod
    @ModelView.button
    @Workflow.transition('dirty')
    def dirty(cls, records):
        Config = Pool().get('hotel.configuration')
        config = Config.get_configuration()
        for rec in records:
            rec.cleaning_type = config.cleaning_occupied.id

    @classmethod
    @ModelView.button
    @Workflow.transition('maintenance')
    def maintenance(cls, records):
        pass

    @classmethod
    @ModelView.button
    @Workflow.transition('inspected')
    def inspected(cls, records):
        pass

    def get_check_in_time(self, name):
        pool = Pool()
        Date = pool.get('ir.date')
        Configuration = pool.get('hotel.configuration')
        BookingFolio = pool.get('hotel.folio')
        config = Configuration.get_configuration()
        lines = BookingFolio.search_read([
            ('room', '=', self.room.id),
            ('arrival_date', '=', Date.today()),
        ], fields_names=['id'])
        if lines:
            return config.check_in_time.strftime('%H:%M %p')

    def get_amenities(self, name=None):
        res = []
        for ame in self.room.amenities:
            res.append(ame.id)
        return res

    def get_check_out_time(self, name):
        # pool = Pool()
        # Date = pool.get('ir.date')
        # Configuration = pool.get('hotel.configuration')
        # Operation = pool.get('hotel.operation')
        # config = Configuration.get_configuration()
        # operations = Operation.search_read([
        #     ('room', '=', self.room.id),
        #     ('end_date', '=', Date.today()),
        # ], fields_names=['id'])
        # if operations:
        #     return config.check_out_time.strftime('%H:%M %p')
        pass

    # def get_occupancies(self, name):
    #     pool = Pool()
    #     OccupancyLine = pool.get('hotel.occupancy.line')
    #     occupancies = set()
    #     lines = OccupancyLine.search([
    #         ('room.id', '=', self.room.id),
    #         ('occupancy.state', '=', 'confirmed'),
    #     ])
    #     for line in lines:
    #         occupancies.add(line.id)
    #     return list(occupancies)
