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 *
import re

# Create your views here.


def index(request):
    rooms = Room.objects.all()
    rooms = rooms.order_by('room_number')
    template = loader.get_template('index.html')

    return HttpResponse(template.render({'rooms': rooms}, request))


def reservation(request):
    room = get_object_or_404(Room, room_number=request.POST['room'])
    template = loader.get_template('reservation.html')
    if not room.reserved:
        room.reserved = True
        room.save()
        status = "Pokój " + str(room) + " zarezerwowany pomyślnie"
    else:
        status = "Pokój " + str(room) + " jest już zarezerwowany"

    return HttpResponse(template.render({'status': status}, request))


def addclient(request):
    error = ""
    if request.method == "POST":
        client = ClientForm(request.POST)
        if client.is_valid():
            if check(client.cleaned_data["id_number"]):
                client.save()
                return HttpResponse()
            error = "Numer dowodu nieprawidłowy"

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


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

    return pattern.match(numer)