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

# 舊方法，應該用 getres

from datetime import datetime

# import collections
import os
import re

from openpyxl import Workbook

OP_DIR  = "/shares/Public/0/OP/"

today = datetime.today()
yymm = today.strftime('%Y-%m')

OUT_XLSX = '/shares/Public/0/%s.xlsx' % yymm


# print(yymm)


pattern = 'Assistants</TD></TR><TR><TD>(.+?)<br>'

R_DICT = {}

def DumpR():
    wb = Workbook()
    ws = wb.active
    for r in sorted(R_DICT.keys()):
        print('%s,%s,%d'% (r, R_DICT[r]['title'], R_DICT[r]['count']))
        ws.append([r, R_DICT[r]['title'], R_DICT[r]['count']])

    wb.save(OUT_XLSX)


def AddR(r):
    r = r.replace('  ', ' ')

    if '陳榮宏' in r:
        print (r)

    if ' ' in r:
        title, name = r.split(' ')
    else:
        title, name = (None, r)

    if name in R_DICT:
        R_DICT[name]['count'] += 1
    else:
        R_DICT[name] = {'count': 1, 'title': ''}

    if title:
        R_DICT[name]['title'] = title

def GetAssistants(filepath):
    f = open(filepath)
    note = f.read()
    f.close()
    # print (note)
    # print(filepath)

    match = re.search(pattern, note)

    if match is None:
        return

    # print (match.group(1))

    for r in match.group(1).split(', '):
        AddR(r.strip())

    # DumpR()
    # exit()

for f in os.listdir(OP_DIR):
    if yymm not in f:
        continue
    filepath = os.path.join(OP_DIR, f)
    GetAssistants(filepath)

DumpR()



