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

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

#from django.conf import settings

import six

if six.PY2:
    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_selenium import Login, SimpleQueryOpSchedule



if six.PY2:
    from BeautifulSoup import BeautifulSoup
else:
    from bs4 import BeautifulSoup

import calendar

#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 GetOperation():
    SESSION=Login()
    for patient in Patient.objects.all():
#    for patient in Patient.objects.filter(id__gte = 5060838):
        ScanOperationNote(patient.id, SESSION)


def ScanOPSchedule(year=False, month=False):

#    OPSchedule.objects.filter(Complete='NO').update(Complete="完成")

    SESSION = Login()

    for ph in Physician.objects.all():
        vs = ph.EmployeeID
        if year:
            if month:
                weakday, number = calendar.monthrange(year, month)
                SaveOP(vs, '%d/%d/1'%(year,month), '%d/%d/%d'%(year,month,number))
            else:
                for month2 in range(1,13):
                    weakday, number = calendar.monthrange(year, month2)
                    SaveOP(vs, '%d/%d/1'%(year,month2), '%d/%d/%d'%(year,month2,number))
        else:
            # starts = date.today() + relativedelta( weeks = -4 )
            starts = date.today() + relativedelta( weeks = -10 )
#            starts = date.today() + relativedelta( weeks = -30 )
            ends = date.today() + relativedelta( weeks = 1 )
            end = ends.strftime("%Y/%m/%d")
            start = starts.strftime("%Y/%m/%d")
            SaveOP(vs, start, end, get_note=True, SESSION=SESSION)
#             if starts.month != ends.month: 
#                 SaveOP(vs, end, end)
#            print vs, start, end
    OPSchedule.objects.filter(Complete__in=['NO', 'OO', 'OO,OS,OE']).update(Complete="完成")



def DumpOPNote():
    output = open('op.txt', 'w')
    for op in OPNote.objects.extra(order_by = ['date']).all():
        print(op.date)
        output.write(strip_tags(op.content).strip() + '\n')
    output.close()
            
        
ScanOPSchedule()

#DumpOPNote()


