from django.http import HttpResponse
from django.template import loader
from django.shortcuts import get_object_or_404, render
from .models import *
from .forms import *
from django.db.models import Q
import datetime
import math
import re

# Create your views here.


def index(request, page=1):
    first_page, last_page = False, False
    if page == 1:
        first_page = True

    rooms = Room.objects.all()
    rooms = rooms.order_by('room_type', 'room_number')

    if page*10 >= len(rooms):
        last_page = True

    max_pages = math.ceil(len(rooms)/10)

    rooms = rooms[10*(page-1):10*page]
    template = loader.get_template('index.html')
    print (first_page,last_page)
    return HttpResponse(template.render({'rooms': rooms,
                                         'firstpage': first_page,
                                         'lastpage': last_page,
                                         'pages': range(1,max_pages+1),
                                         'currentpage': page}, request))


def reservation(request):
    room_number, begin_date, end_date = request.POST['room'], request.POST['begindate'], request.POST['enddate']
    begin_datetime = datetime.datetime.strptime(begin_date, "%d-%m-%Y")
    end_datetime = datetime.datetime.strptime(end_date, "%d-%m-%Y")
    clientform = {}
    template = loader.get_template('reservation.html')
    error = ""
    reservation = Reservation.objects.filter(room_number=room_number).filter(Q(begin_date__range=(begin_datetime, end_datetime)) | Q(end_date__range=(begin_datetime, end_datetime))).first()
    if not reservation is None:
        status = "Pokój " + str(room_number) + " jest zajęty"
        return HttpResponse(template.render({'status': status}, request))

    else:
        if request.method == "POST":

            try:
                client_id = request.POST['id_number']

                if Client.objects.filter(id_number=client_id).first() is None:

                    client = ClientForm(request.POST)
                    if client.is_valid():
                        id_number = client.cleaned_data['id_number']
                        clientform = {'id_number': client.cleaned_data['id_number'],
                                      'name': client.cleaned_data['name'],
                                      'surname': client.cleaned_data['surname']}
                    if check(id_number):
                        client.save()

                        r = Reservation()
                        r.room_number = get_object_or_404(Room, room_number=room_number)
                        r.client_id = get_object_or_404(Client, id_number=client_id)
                        r.begin_date = begin_date
                        r.end_date = end_date
                        r.save()

                        status = "Pokój " + str(room_number) + " został pomyślnie zarezerwowany"
                        return HttpResponse(template.render({'status': status}, request))
                    else:
                        error = "Zły numer dowodu"
            except:
                pass

        form = ClientForm(initial=clientform)
        template = loader.get_template('form.html')
        return HttpResponse(template.render({'form': form,
                                             'error': error,
                                             'room_number': room_number,
                                             'begin_date': begin_date,
                                             'end_date': end_date}, request))

def check(numer):
    pattern = re.compile(r'[A-Z][A-Z][A-Z]\d\d\d\d\d\d')

    return pattern.match(numer)