import datetime

from BookingService.celery import app
from . import models


@app.task
def createBooking(booking):
    b = models.Booking.objects.get(id=booking['id'])
    date = datetime.datetime.strptime(booking['date'], '%Y-%m-%d').date()
    pre_booking_interval_day = models.Setting.objects.get(id=1).pre_booking_interval_day
    today = datetime.datetime.now()
    max_date = today.date() + datetime.timedelta(days=pre_booking_interval_day)
    if date < today.date():
        b.status = 'FAILED'
        b.cancel_reason = f'预约日期超过限制，最早可预约至{date.strftime("%Y-%m-%d")}。'
        b.cancel_datetime = today.strftime('%Y-%m-%d %H:%M:%S')
        b.save()
        return
    if date > max_date:
        b.status = 'FAILED'
        b.cancel_reason = f'预约日期超过限制，最晚可预约至{max_date.strftime("%Y-%m-%d")}。'
        b.cancel_datetime = today.strftime('%Y-%m-%d %H:%M:%S')
        b.save()
        return
    isDuplicate = False
    start_time = datetime.datetime.strptime(booking['start_time'], '%H:%M:%S').time()
    end_time = datetime.datetime.strptime(booking['end_time'], '%H:%M:%S').time()
    for seat in booking['seats']:
        booking_list = models.Booking.objects.filter(room=booking['room'],
                                                     date=booking['date'],
                                                     status='SUCCESS',
                                                     seats__id=seat)
        for item in booking_list:
            if ((start_time >= item.start_time and start_time <= item.end_time)
                    or (end_time >= item.start_time and end_time <= item.end_time)
                    or (start_time <= item.start_time and end_time >= item.end_time)):
                isDuplicate = True
    if isDuplicate:
        b.status = 'FAILED'
        b.cancel_reason = '预约冲突。'
        b.cancel_datetime = today.strftime('%Y-%m-%d %H:%M:%S')
    else:
        b.status = 'SUCCESS'
    b.save()
