#!/usr/bin/xvfb-run python
# -*- coding: utf-8 -*-

import sys
reload(sys)  # Reload does the trick!
sys.setdefaultencoding('utf8')

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ntuh.settings")
import django
django.setup()


from django.db.models.loading import get_models
loaded_models = get_models()

from dateutil.relativedelta import *

from django.db.models import *

# from ntuhgov import xportal
from ntuhgov import portal_spynner
from registry.models import *

import datetime
import json
import shlex
import subprocess
import time

from dateutil.relativedelta import relativedelta


def calculate_age(born):
    today = datetime.date.today()
    try: 
        birthday = born.replace(year=today.year)
    except ValueError: # raised when birth date is February 29 and the current year is not a leap year
        birthday = born.replace(year=today.year, month=born.month+1, day=1)
    if birthday > today:
        return today.year - born.year - 1
    else:
        return today.year - born.year
    

lastyear = today = datetime.date.today()+relativedelta(years=-1)
# print lastyear

FILTER = (Q(HTML__icontains='trauma') 
        | Q(HTML__icontains='brain injur') | Q(HTML__icontains='head injur') 
        | Q(HTML__icontains='concussion') | Q(HTML__icontains='contusion') 
        | Q(HTML__icontains='epidural h') | Q(HTML__contains='EDH')
        | Q(HTML__icontains='subdural h') | Q(HTML__contains='SDH') 
        | Q(HTML__icontains='腦部') | Q(HTML__contains='頭骨') 
          ) 
# FILTER = Q(HTML__icontains='腦部')
#FILTER = Q(HTML__icontains='injury') | Q(HTML__icontains='trauma') | Q(HTML__icontains='epidural') | Q(HTML__icontains='subdural')

for note in DischargeNote.objects.filter(OutDate__gte='2014-09-16', DeptName='外').filter(FILTER).order_by('-OutDate', 'ChartNo'):
    inp = Inpatient.objects.get(ChartNo=note.ChartNo)
    
    age = calculate_age(inp.Birthday)
    print note.ChartNo, age
    
    if not 20 <= age <= 50:
        continue
    
    html_file = 'doc/%s_%s.html' % (note.OutDate, note.ChartNo)
    pdf_file = 'doc/%s_%s.pdf' % (note.OutDate, note.ChartNo)
    
    if os.path.isfile(pdf_file):
        continue 
    
    f = open(html_file, 'w')
    HTML = note.HTML.replace(inp.Name, '*'*len(inp.Name))
    HTML = HTML.replace('<head>', '<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">')
    f.write(HTML)
    f.close
    
    cmd = 'xvfb-run wkhtmltopdf %s %s' % (html_file, pdf_file)
    print cmd
    subprocess.call(shlex.split(cmd))
    time.sleep(1)
        
    
    
    
#     print inp.Name
#     print note.HTML.replace(inp.Name, '*'*len(inp.Name))
#     print note.OutDate
#     exit()
