from django.shortcuts import render, redirect
from backend.models import Patient
from cms.models import Post
from fruit.models import Product
from .forms import SearchForm
from itertools import chain, tee
from operator import attrgetter
from django.db.models import Q
# Create your views here.

def index(request):
    if request.method == "POST":
        print(request.POST)
        print(request.FILES)
        p = Patient()
        p.first_name = request.POST.get('firstName')
        p.last_name = request.POST.get('lastName')
        #p.idcard = request.POST.get('idCard')
        p.address = request.POST.get('address')
        p.geolocation = request.POST.get('geo')
        p.birth_date = request.POST.get('bd')
        p.comment = request.POST.get('comment')
        p.tel = request.POST.get('tel')
        p.line_id = request.POST.get('line_id')
        p.photo = request.FILES.get('photo')
        p.patient_status = "request"
        p.save()
        return redirect('success')
    return render(request, 'front/index.html')

def news(request):
    pass

def forum(request):
    pass

def articles(request):
    pass

def fruit_market(request):
    pass

def agri_market(request):
    pass


def stores(request):
    top_stores = Post.objects.filter(cat__name="Top Stores", status="publish").order_by("-created_at")
    return render(request, "front/stores.html", {'top_stores': top_stores})

def search(request):
    form = SearchForm(request.GET)

    results = None
    if form.is_valid():
        o = form.save(commit = False)
        o.created_by = request.user
        o.save()

        q = Q()
        q2 = Q()
        if o.content_cat != None:
            q = q & Q(cat = o.content_cat)

        if o.product_type != None:
            q2 = q2 & Q(product_type = o.product_type)

        q = q & ( Q(title__contains = o.q ) | Q(body__contains = o.q))
        q2 = q2 & ( Q(name__contains = o.q ) | Q(description__contains = o.q))

        r1 = Post.objects.filter(q)
        r2 = Product.objects.filter(q2)
        results = list(sorted(chain(r1, r2), key = lambda obj: obj.created_at, reverse = True))

    return render(request, "front/search.html", {'form': form, 'results': results})

def mystore(requeset):
    pass


def success(request):
    return render(request, 'front/success.html')

def tracking(request):
    return render(request, 'front/tracking.html')

def my404(request,exception):
    return render(request, 'front/404.html')
    #return redirect("index")

