from django.shortcuts import render
from .models import Task, Request
from .forms import RequestForm
from django.http import HttpResponseRedirect
from django.urls import reverse

def home(request):
    tasks = Task.objects.order_by('order','id')
    return render(request, 'core/home.html', {'tasks': tasks})

def thankyou(request):
    return render(request, 'core/thankyou.html')

def task_detail(request, task_id):
    task = Task.objects.get(id=task_id)
    if request.method == 'POST':
        print("Checking form validity.")
        form = RequestForm(request.POST)
        if form.is_valid():
            print("Form is valid.")
            new_request = form.save()
            # redirect to a new URL:
            return HttpResponseRedirect(reverse('thankyou'))
        else: 
            print(f"Form not valid. Errors: {form.errors}")
    else:
        form = RequestForm(initial={'task': task,'price_from': task.price_from, 'price_to': task.price_to, 'needed_information': task.needed_information,'title': task.title})

    return render(request, 'core/task_detail.html', {'task': task, 'form': form})

#def create_request(request, task_id):
#    if request.method == 'POST':
#        # logic to create a new Request
#        pass
#    else:
#        task = Task.objects.get(id=task_id)
#        request_obj = Request().objects.create(task=task)
#        return render(request, 'core/create_request.html', {'task': task})

def create_request(request, task_id):
    task = Task.objects.get(id=task_id)
    if request.method == 'POST':
        form = RequestForm(request.POST)
        if form.is_valid():
            new_request = form.save()
            # redirect to a new URL:
            return HttpResponseRedirect('/')
    else:
        form = RequestForm(initial={'task': task})

    return render(request, 'core/create_request.html', {'form': form})


def how_it_works(request):
    return render(request, 'core/how_it_works.html')


