from django.shortcuts import render, redirect
from .models import Patient, Detection
from .forms import PatientCreateForm, PatientUpdateForm
from django.contrib import messages
from datetime import datetime
from django.db.models import Q
import subprocess
import os
from PIL import Image
import shutil


# Create your views here.


def home(requset):

    patients = Patient.objects.all().order_by('-created_at')

    return render(requset, 'index.html', {'patients' : patients})


def search(request):
    
    patients = Patient.objects.filter(
        Q(name__contains=request.GET.get('query')) | 
        Q(nationalID__contains=request.GET.get('query'))
        ).order_by('-created_at')

    print('request : ', request)

    return render(request, 'index.html', {'patients': patients})


def patient_create(request):
    if request.method == 'POST':
        print('here')
        form = PatientCreateForm(request.POST, request.FILES)
        print(form)
        if form.is_valid():
            cd = form.cleaned_data
            Patient.objects.create(
                name = cd['name'],
                nationalID = cd['nationalID'],
                image = cd['image'],
                description = cd['description'],
                created_at = datetime.now
            )
            messages.success(request, 'Patient added successfully')

            return redirect('home')
    else:
        form = PatientCreateForm()
    return render(request, 'patient_create.html', {'form': form})


def patient_delete(request, id):
    patient = Patient.objects.get(id=id).delete()
    messages.success(request, 'Patient deleted successfully')
    return redirect('home')



def patient_update(request, id):
    patient = Patient.objects.get(id=id)
    if request.method == 'POST':
        form = PatientUpdateForm(request.POST,request.FILES, instance=patient)
        if form.is_valid():
            form.save()
            messages.success(request, 'Patient updated successfully')
            return redirect('home')
    else:
        form = PatientUpdateForm(instance=patient)
    return render(request, 'patient_update.html', {'form': form})



def patient_detect(request, id):
    patient = Patient.objects.get(id=id)


    # os.system('python detect.py --weights last.pt --img 640 --conf 0.25 --source '+ str(patient.image))

    command = ['python', 'yolov5/detect.py', '--weights', 'last.pt', '--img', '640', '--conf', '0.25', '--source', str(patient.image)]

    subprocess.check_output(command)

    directory = 'yolov5/runs/detect/'

    detected_file_dir = directory + 'exp' + str(len([f for f in os.listdir(directory) if os.path.isdir(os.path.join(directory, f))]))

    image_name = os.path.basename(str(patient.image))
    
    source_file = detected_file_dir + '/' + image_name

    destination_file = 'static/uploads/detections/' + image_name

    shutil.copy(source_file, destination_file)

    detection = Detection.objects.filter(patient = patient)

    if detection.exists():

        detection = detection[0]

        detection.dImage = destination_file

        detection.save()

    else:
        Detection.objects.create(

            patient = patient,
            dImage = destination_file

        )

    detections = Detection.objects.all()

    return render(request, 'detect_list.html', {'detections' : detections})


def detect_list(request):
    detections = Detection.objects.all()

    return render(request, 'detect_list.html', {'detections' : detections})

def detect_view(request, id):
    detection = Detection.objects.get(id=id)

    return render(request, 'detect_view.html', {'detection' : detection})


def detect_delete(request, id):
    detection = Detection.objects.get(id=id).delete()
    messages.success(request, 'Detection deleted successfully')
    return redirect('detect_list')