# Path: demographics/models.py
# class Demographics(models.Model):
# 
#     NULL_BOOLEAN_CHOICES = (
#         (None, "Not Answered"),
#         (True, "Yes"),
#         (False, "No")
#     )
# 
#     patient = models.OneToOneField(Patient, null=True)
# 
#     creation_date = models.DateField(blank=True, null=True)
# 
#     chronic_condition = models.ManyToManyField(ChronicCondition, blank=True)
# 
#     has_insurance = models.NullBooleanField(choices=NULL_BOOLEAN_CHOICES)
# 
#     ER_visit_last_year = models.NullBooleanField(
#         verbose_name="Visited ER in the Past Year",
#         choices=NULL_BOOLEAN_CHOICES)
# 
#     last_date_physician_visit = models.DateField(
#         blank=True, null=True,
#         verbose_name="Date of Patient's Last Visit to Physician or ER")
# 
#     resource_access = models.ManyToManyField(
#         ResourceAccess, blank=True,
#         verbose_name="Access to Resources")
# 
#     lives_alone = models.NullBooleanField(choices=NULL_BOOLEAN_CHOICES)
# 
#     dependents = models.PositiveSmallIntegerField(
#         blank=True, null=True, verbose_name="Number of Dependents")
# 
#     currently_employed = models.NullBooleanField(choices=NULL_BOOLEAN_CHOICES)
# 
#     work_status = models.ForeignKey(WorkStatus, blank=True, null=True)
# 
#     education_level = models.ForeignKey(EducationLevel, blank=True, null=True)
# 
#     annual_income = models.ForeignKey(IncomeRange, blank=True, null=True)
# 
#     transportation = models.ForeignKey(
#         TransportationOption, blank=True, null=True)
# 
#     history = HistoricalRecords()
# 
# Path: demographics/forms.py
# class DemographicsForm(ModelForm):
# 
#     class Meta(object):
#         model = models.Demographics
#         exclude = ['patient', 'creation_date']
#         widgets = {'last_date_physician_visit': DateTimePicker(options={"format": "MM/DD/YYYY"})}
# 
#     def __init__(self, *args, **kwargs):
#         super(DemographicsForm, self).__init__(*args, **kwargs)
# 
#         self.helper = FormHelper()
#         self.helper.form_method = 'post'
# 
#         self.helper.layout = Layout(
#                 Fieldset('Medical',
#                          'has_insurance',
#                          'ER_visit_last_year',
#                          'last_date_physician_visit',
#                          'chronic_condition'),
#                 Fieldset('Social',
#                          'lives_alone',
#                          'dependents',
#                          'resource_access',
#                          'transportation'),
#                 Fieldset('Employment',
#                          'currently_employed',
#                          'education_level',
#                          'work_status',
#                          'annual_income')
#         )
# 
#         self.helper.add_input(Submit('submit', 'Submit'))


import datetime
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
from django.views.generic.edit import FormView, UpdateView
from django.core.urlresolvers import reverse
from django.db import IntegrityError, transaction
from django.forms.models import model_to_dict
from django.shortcuts import render
from .models import Demographics
from .forms import DemographicsForm
from pttrack.models import Patient
    template_name = 'demographics/demographics-create.html'
    form_class = DemographicsForm

    def get_context_data(self, **kwargs):

        context = super(DemographicsCreate, self).get_context_data(**kwargs)

        if 'pt_id' in self.kwargs:
            context['patient'] = Patient.objects.get(pk=self.kwargs['pt_id'])

        return context

    def form_valid(self, form):
        pt = get_object_or_404(Patient, pk=self.kwargs['pt_id'])

        dg = form.save(commit=False)
        dg.creation_date = datetime.date.today()
        dg.patient = pt

        try:
            with transaction.atomic():
                dg.save()
                pt.save()
                form.save_m2m()
                form.save()
            return HttpResponseRedirect(reverse("patient-detail",
                                                args=(pt.id,)))
        except IntegrityError:
            # Create form object containing data from current entry in database
            dg_old = Demographics.objects.get(patient=pt.id)

# Path: demographics/models.py
# class Demographics(models.Model):
# 
#     NULL_BOOLEAN_CHOICES = (
#         (None, "Not Answered"),
#         (True, "Yes"),
#         (False, "No")
#     )
# 
#     patient = models.OneToOneField(Patient, null=True)
# 
#     creation_date = models.DateField(blank=True, null=True)
# 
#     chronic_condition = models.ManyToManyField(ChronicCondition, blank=True)
# 
#     has_insurance = models.NullBooleanField(choices=NULL_BOOLEAN_CHOICES)
# 
#     ER_visit_last_year = models.NullBooleanField(
#         verbose_name="Visited ER in the Past Year",
#         choices=NULL_BOOLEAN_CHOICES)
# 
#     last_date_physician_visit = models.DateField(
#         blank=True, null=True,
#         verbose_name="Date of Patient's Last Visit to Physician or ER")
# 
#     resource_access = models.ManyToManyField(
#         ResourceAccess, blank=True,
#         verbose_name="Access to Resources")
# 
#     lives_alone = models.NullBooleanField(choices=NULL_BOOLEAN_CHOICES)
# 
#     dependents = models.PositiveSmallIntegerField(
#         blank=True, null=True, verbose_name="Number of Dependents")
# 
#     currently_employed = models.NullBooleanField(choices=NULL_BOOLEAN_CHOICES)
# 
#     work_status = models.ForeignKey(WorkStatus, blank=True, null=True)
# 
#     education_level = models.ForeignKey(EducationLevel, blank=True, null=True)
# 
#     annual_income = models.ForeignKey(IncomeRange, blank=True, null=True)
# 
#     transportation = models.ForeignKey(
#         TransportationOption, blank=True, null=True)
# 
#     history = HistoricalRecords()
# 
# Path: demographics/forms.py
# class DemographicsForm(ModelForm):
# 
#     class Meta(object):
#         model = models.Demographics
#         exclude = ['patient', 'creation_date']
#         widgets = {'last_date_physician_visit': DateTimePicker(options={"format": "MM/DD/YYYY"})}
# 
#     def __init__(self, *args, **kwargs):
#         super(DemographicsForm, self).__init__(*args, **kwargs)
# 
#         self.helper = FormHelper()
#         self.helper.form_method = 'post'
# 
#         self.helper.layout = Layout(
#                 Fieldset('Medical',
#                          'has_insurance',
#                          'ER_visit_last_year',
#                          'last_date_physician_visit',
#                          'chronic_condition'),
#                 Fieldset('Social',
#                          'lives_alone',
#                          'dependents',
#                          'resource_access',
#                          'transportation'),
#                 Fieldset('Employment',
#                          'currently_employed',
#                          'education_level',
#                          'work_status',
#                          'annual_income')
#         )
# 
#         self.helper.add_input(Submit('submit', 'Submit'))


# Path: demographics/views.py
import datetime
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
from django.views.generic.edit import FormView, UpdateView
from django.core.urlresolvers import reverse
from django.db import IntegrityError, transaction
from django.forms.models import model_to_dict
from django.shortcuts import render
from .models import Demographics
from .forms import DemographicsForm
from pttrack.models import Patient

    template_name = 'demographics/demographics-create.html'
    form_class = DemographicsForm

    def get_context_data(self, **kwargs):

        context = super(DemographicsCreate, self).get_context_data(**kwargs)

        if 'pt_id' in self.kwargs:
            context['patient'] = Patient.objects.get(pk=self.kwargs['pt_id'])

        return context

    def form_valid(self, form):
        pt = get_object_or_404(Patient, pk=self.kwargs['pt_id'])

        dg = form.save(commit=False)
        dg.creation_date = datetime.date.today()
        dg.patient = pt

        try:
            with transaction.atomic():
                dg.save()
                pt.save()
                form.save_m2m()
                form.save()
            return HttpResponseRedirect(reverse("patient-detail",
                                                args=(pt.id,)))
        except IntegrityError:
            # Create form object containing data from current entry in database
            dg_old = Demographics.objects.get(patient=pt.id)

            form_old = DemographicsForm(dg_old.__dict__)