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


import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'ntuh.settings'

import django
django.setup()


from dateutil.relativedelta import *

import datetime
import json

from django.db.models import *

from ntuhgov.portal_selenium import Login, QueryInPatientByWard
from registry.models import *

import logging
FORMAT = '%(asctime)s %(levelname)s %(message)s'
logging.basicConfig(format=FORMAT, level=logging.INFO)

def ScanWard(ward='08D'):
    logging.info('Scan %s' % (ward))    
    list = QueryInPatientByWard(ward)
    NOW = datetime.datetime.now()
    TIME = NOW.strftime('%Y-%m-%d %H:%M')

    for Pat in list:
        # logging.warning(json.dumps(Pat, indent=1))

        BedID = '%s-%s-%s' % (Pat['WardLabel'], Pat['RoomLabel'], Pat['BedLabel'])
        BedTime = '%s_%s' % (BedID, TIME)
        # logging.info('%s %s'%(BedTime,Pat['PatChartNo']))  
        # lat = InpatientLog.objects.filter(BedID=BedID).latest('Created')
        # print(lat.ChartNo)

        try:
            lat = InpatientLog.objects.filter(BedID=BedID).latest('Created')
        except:
            lat = None

        if lat is None or lat.ChartNo != Pat['PatChartNo']:

            if lat:
                lat.Out = NOW
                lat.save()

            logging.info('create %s %s'%(BedTime,Pat['PatChartNo']))  
            # print(len(BedTime))
            p = InpatientLog.objects.create(BedTime = BedTime)
            p.Ward         = Pat['WardLabel']
            p.Room         = Pat['RoomLabel']
            p.Bed          = Pat['BedLabel'] 
            p.Name         = Pat['LinkPatientName']
            p.ChartNo      = Pat['PatChartNo']
            p.Sex          = Pat['PatientSex']    
            if 'PatientAgeTitle' in Pat: # 'PatientAge': '待確認'
                p.Birthday     = Pat['PatientAgeTitle'][-10:].replace('_', '-')
            p.Age          = Pat['PatientAge']     
            p.HospitalDays = Pat[u'住院總天數'][:-1]
            p.Enter        = Pat[u'入'].replace('/', '-')

            p.BedID        = BedID

            p.save()       

        else:
            logging.info('skip %s %s'%(BedTime,Pat['PatChartNo']))  





        continue
#         print json.dumps(Pat, ensure_ascii=False, indent=1)
        # logging.info(Pat)



        p, created = Inpatient.objects.get_or_create(ChartNo = Pat['PatChartNo'])
        p.Ward         = Pat['WardLabel']
        p.Room         = Pat['RoomLabel']
        p.Bed          = Pat['BedLabel'] 
        p.Name         = Pat['LinkPatientName']
#        p.ChartNo = Pat['ChartNo']
        p.Sex          = Pat['PatientSex']    
        if 'PatientAgeTitle' in Pat: # 'PatientAge': '待確認'
            p.Birthday     = Pat['PatientAgeTitle'][-10:].replace('_', '-')
        p.Age          = Pat['PatientAge']     
        p.HospitalDays = Pat[u'住院總天數'][:-1]
        p.Enter        = Pat[u'入'].replace('/', '-')
        p.save()       

def main():
    ScanWard()

if __name__ == '__main__':
    main()  # 或是任何你想執行的函式
