# -*- coding: utf-8 -*-

if __name__ == "__main__":
    import os
    import sys

    import django
    
    os.environ['DJANGO_SETTINGS_MODULE'] = 'ntuh.settings'
    sys.path.append('../')
    django.setup()

import logging

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

from django.core.exceptions import ObjectDoesNotExist 

from dateutil.relativedelta import relativedelta

# from ntuhgov.portal import operationnotelist, ShowOperationNote

from ntuhgov.portal_selenium import Login, SimpleQueryOpSchedule, OPNoteList, driver

from registry.models import *


import datetime


try:
    import mod_wsgi
    WSGI=True
    # Put code here which should only run when mod_wsgi is being used.
except:
    WSGI=False
    pass


def str2date(str):
    try:
        return datetime.datetime.strptime(str,'%Y/%m/%d')
    except:
        return None

def ScanOperationNote(Chart, SESSION=None, Forced = False):
    if SESSION is None:
        SESSION = Login()

    ChartStr = str(Chart)
    while len(ChartStr) < 7:
        ChartStr='0'+ChartStr
    logging.info(('ScanOperationNote', Chart, ChartStr))

    try:
        opnotes = OPNoteList(ChartStr, SESSION)
    except Exception as e:
        logging.exception(e)
        driver.save_screenshot("screenshot.png")
        exit()

    for item in opnotes:
        if not Forced:
            try:
                op = OPNote.objects.get(KeyCode=item['KeyCode'])
                # print KeyCode[i], 'existed'
                continue
            except:
                pass
        
        try:
            print ('reading', item['KeyCode'])
        except:
            # print i, 'unfinished'
            continue
            
        department, date = item['KeyName'].split('_')
        # content = ShowOperationNote(KeyCode[i], KeyName[i], SESSION)
#            print content
        
#            d = Discharge(Patient.objects.get(id=Chart))
#        op = OPNote(KeyCode[i])
        op, created = OPNote.objects.get_or_create(KeyCode=item['KeyCode'])
        op.PatChartNo  = Chart
#        op.KeyCode     = KeyCode[i]
        op.KeyName     = item['KeyName']
        op.department  = department
        op.date        = str2date(date)
        # op.content     = content
        op.content     = item['reportQuery']
        op.save()







def SaveOP(DrCode, start = False, end = False, get_note=True, SESSION = None, NoCheck=[]):
    if not SESSION:
      SESSION = Login()
    
    if not start:
        (start, end) = prev_bounds()
        
    # print DrCode, start, end
    logging.info((DrCode, start, end))
        
#     year = int(str(start)[:4])
    
    try:
        results = SimpleQueryOpSchedule(DrCode, start, end, SESSION, NoCheck=NoCheck)
    except Exception as e:
        logging.exception(e)
        driver.save_screenshot("screenshot.png")
        exit()
    
    for r in results:
#         ymd = r['OPDate'].split('/')
#         m = int(ymd[-2])
#         d = int(ymd[-1])
        year, m, d = r['OPDate'].split('/')
        
        year = int(year)
        m = int(m)
        d = int(d)
        
        opdate = datetime.date(year, m, d)
        today = datetime.date.today()

        id = '%d/%02d/%02d-%s-%s-%s' % (year, m, d, r['OpRoomNo'], r['OpSeqNo'],r['PatChartNo'])
        
        if not WSGI:
            print (id, r['PatChartNo'], r['Complete'] )

        NeedToClean = False

        # Ignore Hsinchu branch like H171452
        #try:    
        #    PatChartNo = int(r['PatChartNo'])
        #except:
        #    continue
        
        try:
            op = OPSchedule.objects.get(id=id)
        except ObjectDoesNotExist:
            # New records, check candidate records
            ops = OPSchedule.objects.filter(OPDate=opdate, PatChartNo=r['PatChartNo']).exclude(Complete='完成').order_by('id')
            # print len(ops)
            if len(ops):
                NeedToClean = True
                # change the first matching 預計 to 實際
                op = ops[0]
                # print '%s->%s'%(op.id, id)
                op.id = id
            else:
                op = OPSchedule.objects.create(id=id)

        op.OPDate       = opdate
        
        try:       
            op.OpRoomNo     = int(r['OpRoomNo']) 
        except:
            op.OpRoomNo     = r['OpRoomNo']
            pass
                 
        try:       
            op.OpSeqNo      = int(r['OpSeqNo'])
        except:
            pass

        op.PatName      = r['PatName'] 
        op.PatWard      = r['PatWard']    
        op.PatChartNo   = r['PatChartNo']
        op.PatSex       = r['PatSex']          
#        op.PatAge = r['PatAgeTitle']     
        op.PatAge       = r['PatAge']
        
        if op.PatDignosis is None:
            if 'PatDignosisTitle' in r:
                op.PatDignosis  = r['PatDignosisTitle']
            else:
                op.PatDignosis  = r['PatDignosis']
        
        if op.MainOpModeTitle is None and 'MainOpModeTitle' in r:
            op.MainOpModeTitle = r['MainOpModeTitle'] 
            
        op.MainOpMode   = r['MainOpMode']      
        op.OpDoctorName = r['OpDoctorName']    
        op.OpTypeName   = r['OpTypeName']      
        op.Complete     = r['Complete']        
        op.Anes         = r['Anes']            
        op.StartTime    = r['StartTime']       
        op.SpendTime    = r['SpendTime']

        if 'Remark' in r:
           op.Remark    = r['Remark']

        print(op.PatName)
    
        op.save()


        if NeedToClean:
            ops = OPSchedule.objects.filter(OPDate=opdate, PatChartNo=r['PatChartNo']).exclude(Complete='完成').exclude(id=id)
            for op in ops:
                # print "delete %s"%op.id
                op.delete()
#             exit()

#         print "check1 %s %s" % (op.PatChartNo, op.OPDate)
        
        if not get_note:
            continue
        
        if r['PatName'] == 'ｏｏｏ': # Skip VIP
            continue
        
        if r['Complete'] != '完成':
            continue
        
#         print "check2 %s %s" % (op.PatChartNo, op.OPDate)

        POD = (datetime.date.today() - op.OPDate).days
        note_num = len(OPNote.objects.filter(PatChartNo = op.PatChartNo, date = op.OPDate))
        if POD<28 and note_num<1:
            # print "%s %s not existed, do ScanOperationNote" % (op.PatChartNo, op.OPDate)
            ScanOperationNote(r['PatChartNo'], SESSION=SESSION, Forced=True)
        



def SaveOPAllDr(start = False, end = False, get_note=True, SESSION = None, NoCheck=[]):
    if not SESSION:
      SESSION = Login()
    
    if not start:
        (start, end) = prev_bounds()
        
#     year = int(str(start)[:4])

    IDList=[]
    
    for ph in Physician.objects.all():
        DrCode = ph.EmployeeID

        # print DrCode, start, end

        results = SimpleQueryOpSchedule(DrCode, start, end, SESSION, NoCheck=NoCheck)
        
        for r in results:
    #         ymd = r['OPDate'].split('/')
    #         m = int(ymd[-2])
    #         d = int(ymd[-1])
            year, m, d = r['OPDate'].split('/')
            
            year = int(year)
            m = int(m)
            d = int(d)
            
            opdate = datetime.date(year, m, d)
            today = datetime.date.today()
    
            id = '%d/%02d/%02d-%s-%s-%s' % (year, m, d, r['OpRoomNo'], r['OpSeqNo'],r['PatChartNo'])
            IDList.append(id)
            
            if not WSGI:
                print (id, r['PatChartNo'], r['Complete'] )
    
            NeedToClean = False
            
            op, created = OPSchedule.objects.get_or_create(id=id)
    
            op.OPDate       = opdate
            
            try:       
                op.OpRoomNo     = int(r['OpRoomNo']) 
            except:
                pass
                     
            try:       
                op.OpSeqNo      = int(r['OpSeqNo'])
            except:
                pass
                     
            op.PatName      = r['PatName']         
            op.PatWard      = r['PatWard']         
            op.PatChartNo   = r['PatChartNo']      
            op.PatSex       = r['PatSex']          
    #        op.PatAge = r['PatAgeTitle']     
            op.PatAge       = r['PatAge']
            
            if op.PatDignosis is None:
                if 'PatDignosisTitle' in r:
                    op.PatDignosis  = r['PatDignosisTitle']
                else:
                    op.PatDignosis  = r['PatDignosis']
            
            if op.MainOpModeTitle is None and 'MainOpModeTitle' in r:
                op.MainOpModeTitle = r['MainOpModeTitle'] 
                
            op.MainOpMode   = r['MainOpMode']      
            op.OpDoctorName = r['OpDoctorName']    
            op.OpTypeName   = r['OpTypeName']      
            op.Complete     = r['Complete']        
            op.Anes         = r['Anes']            
            op.StartTime    = r['StartTime']       
            op.SpendTime    = r['SpendTime']
    
            if 'Remark' in r:
               op.Remark    = r['Remark']
        
            op.save()
    
            #Will be clean at the end
#             if NeedToClean:
#                 ops = OPSchedule.objects.filter(OPDate=opdate, PatChartNo=r['PatChartNo']).exclude(Complete='完成').exclude(id=id)
#                 for op in ops:
#                     print "delete %s"%op.id
#                     op.delete()
    #             exit()
    
            if not get_note:
                continue
            
            if r['PatName'] == 'ｏｏｏ': # Skip VIP
                continue
            
            if r['Complete'] != '完成':
                continue
    
            POD = (datetime.date.today() - op.OPDate).days
            note_num = len(OPNote.objects.filter(PatChartNo = op.PatChartNo, date = op.OPDate))
            if POD<7 and note_num<1:
                # print "%s %s not existed, do ScanOperationNote" % (op.PatChartNo, op.OPDate)
                ScanOperationNote(r['PatChartNo'], SESSION=SESSION, Forced=True)
        
    # clean up schedule that is not "完成"
#     print sorted(IDList)
#     for s in OPSchedule.objects.filter(OPDate__gte=start, OPDate__lte=end).exclude(Complete='完成').order_by('id'):
    for s in OPSchedule.objects.filter(OPDate__gte=start, OPDate__lte=end, Complete='未執行').order_by('id'):
        if s.id not in IDList:
            # print s.id
            s.delete()



def RenewSchedule():
    SESSION = Login()
    
    # print SESSION
    
    start = datetime.date.today() + relativedelta( days = -1 )
    end = datetime.date.today() + relativedelta( weeks = 1 )

    NoCheck = []
    ops = OPSchedule.objects.filter(OPDate__gte = start, OPDate__lte = end)
    for op in ops:
        if op.Remark:
            NoCheck.append(op.id)

#     print NoCheck
    
    SaveOPAllDr(start, end, get_note=False, SESSION=SESSION, NoCheck=NoCheck)
    
    
if __name__ == "__main__":
    RenewSchedule()

