#!/usr/bin/python
# coding: euc-jp

import cgi
import cgitb
import pyExcelerator
import sys
from datetime import date, datetime, timedelta
import re
from hice import final_output
import time

cgitb.enable()


####################################################################
def int_or_missing(v,i):
    try:
        ret = v[index,i]
    except:
        ret = 0
    return ret

####################################################################
def is_missing(v,i):
    ret=0
    try:
        tmp = v[index,i]
    except:
        ret = 1
    return ret

####################################################################
def errorpage(str):
    print """Contetn-type: text/plain

%s
""" % (str)
    exit(0)

####################################################################
def cmppid(x,y):
    return int(x['pid'])-int(y['pid'])

####################################################################
def html_table_head():
    return  "      <h2 class=\"%(h2class)s\">%(faculty)s %(program)s</h2>\n      <table class=\"videolist\">\n"

####################################################################
def html_table_body():
    return """%(html_head)s
        <tr valign="top">
          <td class="thumbnail"><a href="video.cgi?cid=%(code)s&amp;size=l&amp;nv=1&amp;f=%(request_fac)s"><img src="thumb/%(code)s.png" width="160" height="90" class="thumbnail" alt="thumbnail"></a></td>
          <td>
             <a href="video.cgi?cid=%(code)s&amp;size=l&amp;nv=1&amp;f=%(request_fac)s" class="title">%(course)s</a>%(new)s<br>
             %(duration)s/%(recdate)s 撮影/%(pubdate)s 公開<br>
             担当教員：%(prof)s (%(affil)s)<br>
             授業形式：<span class="%(is_kougi)s">講義</span> <span class="%(is_jisshu)s">実習</span> <span class="%(is_sonota)s">その他</span><br>
             対象学年：<span class="%(grd1)s">1</span> <span class="%(grd2)s">2</span> <span class="%(grd3)s">3</span> <span class="%(grd4)s">4</span> <span class="%(grd5)s">5</span> <span class="%(grd6)s">6</span>  開講時期：<span class="%(is_zenki)s">前期</span> <span class="%(is_kouki)s">後期</span> <span class="%(is_shuchu)s">集中</span> <br><br>
          </td>
          <td><br>
            <img src="album.gif" alt="*"> <a href="%(syllabus)s">シラバス参照</a><br>
            <img src="film.gif" alt="*"> <a href="video.cgi?cid=%(code)s&amp;size=l&amp;nv=1&amp;f=%(request_fac)s">授業動画(大)</a><br>
            <img src="film.gif" alt="*"> <a href="video.cgi?cid=%(code)s&amp;size=s&amp;nv=1&amp;f=%(request_fac)s">授業動画(小)</a><br>
        </tr>
"""

####################################################################
def syllabus_url(cid):
    m=re.compile("^(([0-9]{4})_[A-Z0-9]+_[A-Z0-9]+)(_[A-Z0-9]+)?$").match(cid)
    if not m:
        return ""

    if m.group(3):
        cid = m.group(1)

    this_year  =  int(datetime.today().strftime("%Y"))
    this_month =  int(datetime.today().strftime("%m"))

    if this_month<3:
        this_school_year = this_year-1
    else:
        this_school_year = this_year

    if int(m.group(2)) == this_school_year:
        return "https://momiji.hiroshima-u.ac.jp/syllabus/%s.html" % cid
    else:
        return "syllabus/%d/%s.html" % (int(m.group(2)),cid)

####################################################################
# ビデオクリップの継続時間を調べる

fd = open("data/flvstat.dat","r")
p = re.compile("^(.*)-l.flv")
duration={}

for line in fd.readlines():
    items=line.split()
    result = p.match(items[0])
    if result:
        cid = result.group(1)
        t = items[2].split(":")
        if int(t[0])>0:
            duration[cid] = "%d 時間 %d 分" % (int(t[0]),int(t[1]))
        else:
            duration[cid] = "%d 分" % (int(t[1]))

fd.close()

####################################################################
cgiinput = cgi.FieldStorage()
try:
    request_prog = int(cgiinput.getfirst("p","-1"))
except:
    request_prog = -1


if request_prog==-1:
    try:
        request_fac = int(cgiinput.getfirst("f","-1"))
    except:
        request_fac = -1
else:
    request_fac = -1


#request_size = cgiinput.getfirst("size","l")

#request_id = "2010_050102_F3059135"
#request_size = "l"


sheets = pyExcelerator.parse_xls('data/hoc_prog.xls')

html=""
prevpid=0
in_table=0
fac_color=("sou","bun","kyo","hou","kei","ri","i","shi","kou","sei","yaku","sonota")
hi_dis=("hi","dis")

kogi_list=[]

for sheet_name, values in sheets:
    if sheet_name != u'2010' and sheet_name != u'2011':
        continue

    for index in xrange(1,1000):
        d={}
        d['request_fac']=request_fac

        # 学部が書いてないところで終了
        try:
            d['faculty']=values[index,0].encode("euc-jp")
        except:
            break

        # 公開されているものをリストに残す
        try:
            tmp=values[index,33]
        except:
            continue

        # pid を調べる(request_fac=-1ならフィルタなし）
        # pid / 100 が部局を示す。1=総合科学部 2=文学部…
        pid = int(values[index,7])

#        if request_prog>0:
#            if pid != request_prog:
#                continue
#        else:
#            if request_fac>0:
#                if ( int( pid / 100 ) ) != request_fac:
#                    continue


        # course id (講義コード)を調べる
        try:
            d['code']=values[index,3].encode("euc-jp")
        except:
            continue

        d['program']=values[index,1].encode("euc-jp")
        d['course']=values[index,2].encode("euc-jp")
        d['prof']=values[index,4].encode("euc-jp")
        d['affil']=values[index,6].encode("euc-jp")
        try:
            tmpdate = date(1904,1,1)+timedelta(values[index,8])
            d['recdate']="%d年%d月%d日" % (tmpdate.year,tmpdate.month,tmpdate.day)
        except:
            d['recdate']="--年--月--日"

        d['pid']=values[index,7]

        d['is_kougi']=hi_dis[is_missing(values,35)]
        d['is_jisshu']=hi_dis[is_missing(values,36)]
        d['is_sonota']=hi_dis[is_missing(values,37)]

        # d['grade'] は、対象学年のリストになる
        try:
            d['grade']=[int(values[index,38])]
        except:
            try:
                d['grade']=[int(x) for x in values[index,38].split(",")]
            except:
                d['grade']=()

        # d['grade'] に上げられた学年をハイライトする（cssのclassを"hi"に)
        for tmpg in xrange(1,7):
            d["grd%d" % (tmpg)]="dis"

        for tmpg in d['grade']:
            d["grd%d" % (tmpg)]="hi"

        d['is_zenki']=hi_dis[is_missing(values,39)]
        d['is_kouki']=hi_dis[is_missing(values,40)]
        d['is_shuchu']=hi_dis[is_missing(values,41)]
        d['new']=''

        d['syllabus']=syllabus_url(d['code'])

        try:
            tmpdate = date(1904,1,1)+timedelta(values[index,42])
            d['pubdate']="%d年%d月%d日" % (tmpdate.year,tmpdate.month,tmpdate.day)
            deltafromtoday = date.fromtimestamp(time.time())-tmpdate
            if deltafromtoday.days<30:
                d['new']=' <span class="new">new!</span>'
#            elif request_fac==-3:
#                continue
        except:
            d['pubdate']="--年--月--日"

        try:
            d['h2class']=fac_color[int(pid/100)-1]
        except:
            d['h2class']='sou'


        try:
            d['duration'] = duration[d['code']]
        except:
            d['duration'] = "--時間--分"


        kogi_list.append(d)


kogi_list.sort(cmppid)


for d in kogi_list:
    if request_prog>0:
        if d['pid'] != request_prog:
            continue
    else:
        if request_fac>0:
            if ( int( d['pid'] / 100 ) ) != request_fac:
                continue
        elif request_fac==-3:
            if d['new'] == "":
                continue

    d['html_head']=""
    if prevpid != d['pid']:
        if in_table==1:
            d['html_head'] ="      </table>"
        d['html_head'] += html_table_head() % d
        in_table=1

    html += html_table_body() % d
    prevpid=d['pid']


if in_table==1:
    html += "</table>"

final_output(request_fac,html)


#
