from django.shortcuts import render, redirect
from .models import Project, Tag
from django.contrib.auth.decorators import login_required
from .forms import ProjectForm

from django.db.models import Q
from .utils import searchProjects, paginationProjects


def projects(request):
    projects, search_query = searchProjects(request)
    custom_range, projects = paginationProjects(request, projects, 5)

    context = {'projects':projects, 'search_query':search_query, 'custom_range':custom_range}

    return render(request, 'projects/projects.html', context)


def singleProjects(request, pk):
    querySingle = Project.objects.get(id=pk)


    return render(request, 'projects/single-project.html', {'querySingle':querySingle})

@login_required(login_url='login')
def createProject(request):
    profile = request.user.profile
    form = ProjectForm()

    if request.method == 'POST':
        form = ProjectForm(request.POST)
        if form.is_valid():
            project = form.save(commit=False)
            project.owner = profile
            project.save()
            return redirect('projects')
        

    context = {'form':form}
    return render(request, 'projects/project_form.html', context)

@login_required(login_url='login')
def updateProject(request, pk):
    profile = request.user.profile
    project = profile.project_set.get(id=pk)
    form = ProjectForm(instance=project)

    if request.method == 'POST':
        form = ProjectForm(request.POST, instance=project)
        if form.is_valid():
            form.save()
            return redirect('projects')
        

    context = {'form':form}
    return render(request, 'projects/project_form.html', context)

@login_required(login_url='login')
def deleteProject(request, pk):
    profile = request.user.profile
    project = profile.project_set.get(id=pk)
    if request.method == 'POST':
        project.delete()
        return redirect('projects')
    context = {'object':project}
    return render(request, 'delete_template.html', context)




