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

### 虞希禹要的 --- 全外科 --- 目前沒在用

# from django.core.management import setup_environ
# import settings
# setup_environ(settings)

#from django.conf import settings

CSV_FILE = "/shares/Public/2018/172_16_3_33_389.csv"
OUT_DIR  = "/shares/Public/0/OP/"

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

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'ntuh.settings'
# 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 pprint import pprint
from datetime import date, datetime, timedelta 
from dateutil.relativedelta import *

#from django.utils.html import strip_tags
#from django.core.exceptions import ObjectDoesNotExist
#from django.template.defaultfilters import removetags

#from registry.models import *
#from registry.utils import SaveOP
# from ntuhgov.portal_spynner import Login, SimpleQueryOpSchedule

from ntuhgov.portal import operationnotelist, ShowOperationNote
from ntuhgov.portal_selenium import Login, SimpleQueryOpSchedule

from BeautifulSoup import BeautifulSoup

import csv
import calendar
import re

#def strip_tags(page):
#    return ' '.join(BeautifulSoup(page).findAll(text=True))


def strip_tags(source): #strip the <script> tag
    soup = BeautifulSoup(source)
    to_extract = soup.findAll('script')
    for item in to_extract:
        item.extract()
#        print soup
#        exit()
    return ' '.join(soup.findAll(text=True))

def prev_bounds(when=None): 
    if not when: when = datetime.datetime.today() 
    this_first = date(when.year, when.month, 1) 
    prev_end = this_first - timedelta(days=1) 
    prev_first = date(prev_end.year, prev_end.month, 1) 
    return prev_first.strftime("%Y/%m/%d"), prev_end.strftime("%Y/%m/%d")  


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

    if SESSION is None:
        SESSION=Login()

    ChartStr = str(Chart)
    while len(ChartStr) < 7:
        ChartStr='0'+ChartStr
#    print Chart, ChartStr

    KeyCode, KeyName = operationnotelist(ChartStr, SESSION)
#    try:
##        KeyCodeList, KeyNameList = operationnotelist(ChartStr, SESSION)
#        KeyCode, KeyName = operationnotelist(ChartStr, SESSION)
#    except:
#        return

#    KeyCode = KeyCodeList.split('|')
#    KeyName = KeyNameList.split('|')
    
    for i in range(len(KeyCode)):
        department, date = KeyName[i].split('_')
        workfile = '%s/%s.%s.%s.html' % (OUT_DIR, KeyCode[i], KeyName[i].replace('/','-'), Chart)
        if os.path.isfile(workfile):
            print('%s..........skipped' % workfile)    
            continue

        content = ShowOperationNote(KeyCode[i], KeyName[i], SESSION)

        if 'Assistants' not in content:
            print('%s..........skipped' % workfile)    
            continue

        print(workfile)    

        f = open(workfile, 'w')
        f.write(content)
        f.close()
        # exit()
        

def DumpOPNote(PatSet):

    for p in sorted(PatSet):
        ScanOperationNote(p)
        # exit()

def GetOP(DrCode):

    PatSet = set()

    # print('Getting ', DrCode)

    today = datetime.today()

    year  = today.year
    month = today.month

    start = '%d/%d/1' % (year, month)
    end   = '%d/%d/%d'% (year, month, calendar.monthrange(year, month)[1])

    results = SimpleQueryOpSchedule(DrCode, start, end)

    for r in results:
        PatSet.add(r['PatChartNo'])

    # print (results)
    # print(len(results), len(PatSet))
    # if results:
        # pprint(results[0])
        # exit()

    return PatSet

# http://ihisaw.ntuh.gov.tw/WebApplication/InPatient/OPManagement/OPNoteInsertUpdate_V2.aspx?SESSION=47F69BA83CE5ED472AA203B9CE3CFC8B91&OperationIDSE=2017-T0-114640


VS_LIST = []

def ReadCN():

    pattern = 'CN=(\d+),'

    with open(CSV_FILE) as csvfile:
        # spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
        spamreader = csv.reader((line.replace('\0','') for line in csvfile), delimiter=',', quotechar='"')
        for row in spamreader:
            join_row = ', '.join(row)
            if '主治醫師' in join_row:
                m = re.search(pattern, join_row)
                CN = m.group(1)
                VS_LIST.append(CN)

                # print(join_row)
                # print(CN)

                # exit()
            # print(', '.join(row))

    print(sorted(VS_LIST))
    # print (len(VS))

    for vs in sorted(VS_LIST):
        PatSet = GetOP(vs)
        print(vs, sorted(PatSet))
        if PatSet:
            DumpOPNote(PatSet)
            # exit()


        


ReadCN()
exit()
ScanOPSchedule()

#DumpOPNote()


