# Create your views here.

from django.contrib.auth.decorators import login_required
# from django.core.urlresolvers import reverse_lazy
from django.urls import reverse_lazy
from django.shortcuts import *
from django.views.generic import *
from django.views.generic.edit import *

from .forms import *
from .models import *

import ck.models

import logging
logger = logging.getLogger(__name__)

#@login_required
class PatientList(ListView):
    model = NPatient

class PatientDetail(DetailView):
    model = NPatient

class PatientUpdate(UpdateView):
    model = NPatient
    form_class = NPatientForm # for exclude
    
    def get_success_url(self):
        return reverse('patient_detail', kwargs={'pk': self.object.Patient.id})


class PatientDelete(DeleteView):
    model = NPatient
    success_url = reverse_lazy('patient_list') 

class TargetDetail(DetailView):
    model = NTarget

class TargetUpdate(UpdateView):
    model = NTarget
    form_class = NTargetForm # for exclude
    
    def get_success_url(self):
        return reverse('patient_detail', kwargs={'pk': self.object.Lesion.treatment.patient.id})


class TargetDelete(DeleteView):
    model = NTarget
#    success_url = reverse_lazy('patient_detail') 
    def get_success_url(self):
        return self.request.POST['next']
#        return reverse('patient_detail', kwargs={'pk': self.object.Lesion})


@login_required
def add(request):
    if request.method == 'POST': # If the form has been submitted...
        chartno = request.POST.get('ChartNo', None)
        name = request.POST.get('Name', None)
        idcode = request.POST.get('idcode', None)
        
        if chartno:
            np = NPatient.objects.filter(Patient__medical_records=chartno)
        elif name:
            np = NPatient.objects.filter(Patient__name=name)
        elif idcode:
            np = NPatient.objects.filter(Patient__id_cards=idcode)
        if len(np)==1:
            return redirect(reverse('patient_detail', args=(np[0].Patient.id,)))
            

        if chartno:
            p = ck.models.Patient.objects.filter(medical_records=chartno)
        elif name:
            p = ck.models.Patient.objects.filter(name=name)
        elif idcode:
            p = ck.models.Patient.objects.filter(id_cards=idcode)
            
        # print p
        logging.info(p)
        
        if len(p) == 1:
            np = NPatient(Patient = p[0])
#                np = NPatient()
#                np.Patient = p[0]
            np.save()
            return redirect(np)

    form = CollectForm() # An unbound form

    return render(request, 'nsclc/add.html',
                  {
                   'form': form,
                   })

@login_required
def TargetAdd(request, pk):
    l = ck.models.Lesion.objects.get(id = pk)
    t = NTarget(Lesion = l)
    t.save()
    return redirect(t)
    
