#!/usr/bin/python
# coding: UTF-8
# Rec10 TS Recording Tools
# Copyright (C) 2009 Yukikaze
import cgi
import cgitb
import rec10web_dbMySQL
import os
import os.path
import re
import datetime
import ConfigParser
import time
cgitb.enable()
path = str(os.path.dirname(os.path.abspath(__file__))) + "/"
confp = ConfigParser.SafeConfigParser()
Conf = 'rec10.conf'
cpath=""
if (os.path.exists(os.path.join(path,Conf))):
    cpath=os.path.join(path,Conf)
elif (os.path.exists(os.path.join("/etc/rec10",Conf))):
    cpath=os.path.join("/etc/rec10",Conf)
elif (os.path.exists(os.path.join("/etc",Conf))):
    cpath=os.path.join("/etc",Conf)

confp.read(cpath)
global f
f = cgi.FieldStorage()
def getpath(string):
    global confp
    return confp.get('path', string)
def getdbpath(string):
    global confp
    return confp.get('db', string)
def getdb():
    retdb = ""
    if getdbpath('db') == 'MySQL':
        dbn = getdbpath("mysql_dbname")
        dbh = getdbpath("mysql_host")
        dbu = getdbpath("mysql_user")
        dbpwd = getdbpath("mysql_passwd")
        dbport = int(getdbpath("mysql_port"))
        retdb = rec10web_dbMySQL.DB_MySQL(dbname=dbn, host=dbh, user=dbu, passwd=dbpwd, port=dbport)
    return retdb
def getRecDate():
    dl = database.select_all_timeline()
    recdata = "id,type,chtxt,title,btime,etime,deltaday,opt\n"
    #print dl
    for d in dl:
        id = d['id']
        typet = d['type']
        chtxt = d['chtxt']
        title = d['title']
        btime = d['btime']
        etime = d['etime']
        deltatime = d['deltatime']
        deltaday = d['deltaday']
        opt = d['opt']
        if deltaday == None:
            deltaday = u"なし"
        elif deltaday == "":
            deltaday = u"なし"
        if opt == None:
            opt = u"なし"
        if typet == "reserve_flexible":
            typet = u"浮動予約"
        elif typet == "search_today":
            typet = u"当日予約"
        elif typet == "search_everyday":
            typet = u"隔日予約"
        elif typet == "reserve_fixed":
            typet = u"確定予約"
        elif typet == "grid":
            typet = u"外部委託"
        elif typet == "convert_ts_mp4":
            typet = u"縁故予約"
        elif typet == "convert_b25_ts":
            typet = u"解読予約"
        #print btime
        btime = btime[5:16]
        etime = etime[5:16]
        btime = btime.replace("-", "/")
        etime = etime.replace("-", "/")
        if btime[0:5] == etime[0:5]:
            etime = etime[6:]
        s = "\"" + str(id) + "\",\"" + typet + "\",\"" + chtxt + "\",\"" + title + "\",\"" + btime + "\",\"" + etime + "\",\"" + deltaday + "\",\"" + opt + "\"\n"
        s = str(id) + "," + typet + "," + chtxt + "," + title + "," + btime + "," + etime + "," + deltaday + "," + opt + "\n"
        recdata = recdata + s
    f = open(path + "/recdatum.csv", "w")
    f.write(recdata.encode('utf-8'))
    f.close()
def getiEPGDate():
    dl = database.select_all_iepg()
    recdata = "id,name,chtxt\n"
    #print dl
    s = ""
    for d in dl:
        s = s + d[0] + "," + d[1] + "," + d[2] + "\n"
    recdata = recdata + s
    f = open(path + "/iepgdatum.csv", "w")
    f.write(recdata.encode('utf-8'))
    f.close()
def getchtxt():
    dl = database.select_all_epg_ch()
    chopt = ""
    for bctype, ontv, chtxt, chname, ch, csch, updatetime in dl:
        chopt = chopt + "<option  value=" + chtxt + ">" + chname + "</option>\n                "
    return chopt
def edit_date(id):
    ret = database.select_by_id_timeline(id)
    return ret[0]
def reserv_recday(keyword, chtxt, btime, etime, deltatime, opt, deltaday, day):
    """
    dayは月曜日を1日曜日を7とした数字
    """
    #bt=datetime.datetime.strptime(btime,"%Y-%m-%d %H:%M:%S")
    #et=datetime.datetime.strptime(etime,"%Y-%m-%d %H:%M:%S")
    bt = datetime.datetime(*time.strptime(btime, "%Y-%m-%d %H:%M:%S")[:-3])
    et = datetime.datetime(*time.strptime(etime, "%Y-%m-%d %H:%M:%S")[:-3])
    dt = int(day)-bt.isoweekday()
    if dt < 0:
        dt = dt + 7
    dbt = bt + datetime.timedelta(days=dt)
    det = et + datetime.timedelta(days=dt)
    btime = dbt.strftime("%Y-%m-%d %H:%M:%S")
    etime = det.strftime("%Y-%m-%d %H:%M:%S")
    return reserv("keyevery", keyword, chtxt, btime, etime, deltatime, opt, "7")
def reserv(type, keyword, chtxt, btime, etime, deltatime, opt, deltaday):
    MaxT = 2
    MaxS = 2
    tsnum = count_schedule(btime, etime)
    MaxT = MaxT-tsnum[0]
    MaxS = MaxS-tsnum[1]
    bctype = ""
    rett = ""
    bctypegetdb = database.select_by_chtxt_epg_ch(chtxt)
    for bctypet, ontvt, chtxtt, cht, cscht, updatetimet in bctypegetdb:
        bctype = bctypet
    if (type == "reserve_fixed") or (type == "reserve_flexible") or (type == "search_today") or (type == "search_everyday"):
        if bctype.find("cs") > -1:
            MaxS = MaxS-1
        elif bctype.find("bs") > -1:
            MaxS = MaxS-1
        elif bctype.find("te") > -1:
            MaxT = MaxT-1
    if MaxS > -1 and MaxT > -1:
        database.add_timeline(type=type, chtxt=chtxt, title=keyword, btime=btime, etime=etime, deltatime=deltatime, deltaday=deltaday, opt=opt)
        rett = ""
    else:
        rett = "over"
    return rett
def count_schedule(btime, etime):
    """
    return rec num (int return[0]:TE /int return[1]:BS/CS)
    """
    def cmpare(x, y):
        #xt=datetime.datetime(*time.strptime(x,"%Y-%m-%d %H:%M:%S")[:-3])
        #yt=datetime.datetime(*time.strptime(y,"%Y-%m-%d %H:%M:%S")[:-3])
        xt = x
        yt = y
        if xt > yt:
            return -1
        elif xt == yt:
            return 0
        else:
            return 1
    dls = database.schedule_timeline(btime, etime)
    times = []
    btd = datetime.datetime(*time.strptime(btime, "%Y-%m-%d %H:%M:%S")[:-3])
    etd = datetime.datetime(*time.strptime(etime, "%Y-%m-%d %H:%M:%S")[:-3])
    for dl in dls:
        dd1 = datetime.datetime(*time.strptime(dl[4], "%Y-%m-%d %H:%M:%S")[:-3])
        dd2 = datetime.datetime(*time.strptime(dl[5], "%Y-%m-%d %H:%M:%S")[:-3])
        if dd1 < btd:
            dd1 = btd
        if dd2 > etd:
            dd2 = etd
        times.append(dd1)
        times.append(dd2)
    times = list(set(times))
    times.sort(cmpare)
    times.reverse()
    retcount = [0, 0]
    for i in xrange(0, len(times)-2, 1):
        bt1 = times[i]
        et1 = times[i + 1]
        btime1 = bt1.strftime("%Y-%m-%d %H:%M:%S")
        etime1 = et1.strftime("%Y-%m-%d %H:%M:%S")
        ret1 = database.count_schedule_timeline(btime1, etime1)
        if retcount[0] < ret1[0]:
            retcount[0] = ret1[0]
        if retcount[1] < ret1[1]:
            retcount[1] = ret1[1]
    return retcount
def change_reserv(id, type, keyword, chtxt, btime, etime, deltatime, opt, deltaday):
    """
    idはテキスト
    """
    MaxT = 2
    MaxS = 2
    tsnum = count_schedule(btime, etime)
    MaxT = MaxT-tsnum[0]
    MaxS = MaxS-tsnum[1]
    bctype = ""
    rett = ""
    for dl in database.select_by_chtxt_epg_ch(chtxt):
        bctype = dl[0]
    if (type == "reserve_fixed") or (type == "reserve_flexible") or (type == "search_today") or (type == "search_everyday"):
        if bctype.find("cs") > -1:
            MaxS = MaxS-1
        elif bctype.find("bs") > -1:
            MaxS = MaxS-1
        elif bctype.find("te") > -1:
            MaxT = MaxT-1
    if MaxS > -1 and MaxT > -1:
        database.del_by_id_timeline(id)
        database.add_timeline(type=type, chtxt=chtxt, title=keyword, btime=btime, etime=etime, deltatime=deltatime, deltaday=deltaday, opt=opt)
    else:
        rett = "over"
    return rett
def station2chtxt(station):
    ret = ""
    #try:
    database.new_iepg()
    #except:
    #    ""
    sta = database.select_by_station_iepg(station)
    if len(sta) > 0:
        ret = sta[0][2]
    else:
        ret = "n\/a"
    return ret
def readHtmlSrcSimple():
    f = open(path + 'rswi.htm')
    ret = f.read()
    f.close()
    return unicode(ret,'utf-8')
def readRecFinisSimple():
    f = open(path + 'fin.htm')
    ret = f.read()
    f.close()
    return unicode(ret,'utf-8')
def readRecSchedule():
    f = open(path + 'schedule.htm')
    ret = f.read()
    f.close()
    return unicode(ret,'utf-8')
def readiEPGadd():
    f = open(path + 'iepg_add.htm')
    ret = f.read()
    f.close()
    return unicode(ret,'utf-8')
def readiEPGshow():
    f = open(path + 'iepg_show.htm')
    ret = f.read()
    f.close()
    return unicode(ret,'utf-8')
def get_fin(string, refreshurl):
    htmdate = readRecFinisSimple()
    htmdate = htmdate.replace('<!--text_for_replace_fin//-->', string)
    htmdate = htmdate.replace('<!--url_for_replace_fin//-->', refreshurl)
    return htmdate
def mode_iepg_add(station):
    htmdate = readiEPGadd()
    htmdate = htmdate.replace("<!--text_for_replace_chtxt_input//-->", getchtxt())
    htmdate = htmdate.replace("<!--ch-value//-->", "")
    htmdate = htmdate.replace("<!--iepg_title-value//-->", station)
    return htmdate
def mode_iepg_fin():
    s = u"epgデータの追加を完了しました。<br>\n録画を行う場合はもう一度おねがいします。<br>"
    u = "rec10web.py?exec=iepg-show"
    return get_fin(s, u)
def mode_iepg_show():
    htmdate = readiEPGshow()
    return htmdate
def mode_iepg_del():
    s = u"epgデータを削除しました。"
    u = "rec10web.py?exec=iepg-show"
    return get_fin(s, u)
def mode_iepg_del_miss():
    s = u"epgデータの削除に失敗しました。"
    u = "rec10web.py?exec=iepg-show"
    return get_fin(s, u)
def mode_schedule():
    htmdate = readRecSchedule()
    return htmdate
def mode_recfin():
    s = u"予約が終了しました。移動します。"
    u = "rec10web.py?exec=schedule"
    return get_fin(s, u)
def mode_recover():
    s = u"最大予約可能数を超えています"
    u = "rec10web.py?exec=schedule"
    return get_fin(s, u)
def mode_normal():
    htmdate = readHtmlSrcSimple()
    htmdate = htmdate.replace("<!--exec-value//-->", "yes")
    return htmdate
def mode_del():
    s = u"予約を削除しました。"
    u = "rec10web.py?exec=schedule"
    return get_fin(s, u)
def mode_edit_rec10web(tasknum):
    #editnum=exect.replace("edit:","")
    htmdate = readHtmlSrcSimple()
    iddata = edit_date(tasknum)
    htmdate = htmdate.replace("<!--text_for_replace_chtxt_input//-->", getchtxt())
    htmdate = htmdate.replace("<!--ch-value//-->", iddata['chtxt'])
    htmdate = htmdate.replace("<!--btime-value//-->", iddata['btime'])
    htmdate = htmdate.replace("<!--etime-value//-->", iddata['etime'])
    htmdate = htmdate.replace("<!--type-value//-->", iddata['type'])
    htmdate = htmdate.replace("<!--ch-value//-->", iddata['chtxt'])
    htmdate = htmdate.replace("<!--title-value//-->", iddata['title'])
    htmdate = htmdate.replace("<!--size-value//-->", size)
    htmdate = htmdate.replace("<!--opts-value//-->", iddata["opt"])
    htmdate = htmdate.replace("<!--exec-value//-->", "edit-exec:" + tasknum)
    return htmdate
def mode_edit():
    editnum = exect.replace("edit:", "")
    htmdate = readHtmlSrcSimple()
    iddata = edit_date(editnum)
    htmdate = htmdate.replace("<!--text_for_replace_chtxt_input//-->", getchtxt())
    htmdate = htmdate.replace("<!--ch-value//-->", iddata['chtxt'])
    htmdate = htmdate.replace("<!--btime-value//-->", iddata['btime'])
    htmdate = htmdate.replace("<!--etime-value//-->", iddata['etime'])
    htmdate = htmdate.replace("<!--type-value//-->", iddata['type'])
    htmdate = htmdate.replace("<!--ch-value//-->", iddata['chtxt'])
    htmdate = htmdate.replace("<!--title-value//-->", iddata['title'])
    htmdate = htmdate.replace("<!--size-value//-->", size)
    htmdate = htmdate.replace("<!--opts-value//-->", iddata["opt"])
    htmdate = htmdate.replace("<!--exec-value//-->", "edit-exec:" + editnum)
    return htmdate
dbpath = path + "ch.db"
database = getdb()
btime = ""
etime = ""
title = ""
chtxt = ""
type = "reserve_flexible"
bt = ""
station_name = ""
mode = ""
###ここからiEPG用の読み出し
if f.getfirst('station_name'):
    station = f.getfirst('station_name')
    chtxt = station2chtxt(station)
    if chtxt == "n\/a":
        mode = "iepg-add"
        station_name = station
        exect = "iepg-add"
if f.getfirst('station'):
    station = f.getfirst('station')
    chtxt = station2chtxt(station)
    if chtxt == "n\/a":
        mode = "iepg-add"
        station_name = station
        exect = "iepg-add"
###ここから外部からの読み出しの場合
if f.getfirst('type'):
    type = unicode(f.getfirst('type'),'utf-8')
if f.getfirst('title'):
    title = unicode(f.getfirst('title'),'utf-8')
if f.getfirst('chtxt'):
    chtxt = unicode(f.getfirst('chtxt'),'utf-8')
if f.getfirst('btime'):
    btime = unicode(f.getfirst('btime'),'utf-8')
    bt = datetime.datetime(*time.strptime(btime, "%Y-%m-%d %H:%M:%S")[:-3])
if f.getfirst('etime'):
    etime = unicode(f.getfirst('etime'),'utf-8')
    et = datetime.datetime(*time.strptime(etime, "%Y-%m-%d %H:%M:%S")[:-3])
    if bt != "":
        delt = et-bt
        dt = delt.days * 24 * 60 * 60 + delt.seconds
        if dt < 0:
            dd = datetime.timedelta(days=1)
            et = et + dd
            etime = unicode(et.strftime("%Y-%m-%d %H:%M:%S"),'utf-8')
        if dt < -1 * 24 * 60 * 60:
            d1 = datetime.datetime(bt.year, 0, 0)
            d2 = datetime.datetime(bt.year + 1, 0, 0)
            dd = d2-d1
            et = et + dd
            etime = unicode(et.strftime("%Y-%m-%d %H:%M:%S"),'utf-8')
size = "S"
if f.getfirst('size'):
    size = f.getfirst('size')
opts = ""
if f.getfirst('opts'):
    opts = f.getfirst('opts')
deltahour = ""
if f.getfirst('deltahour', ""):
    deltahour = f.getfirst('deltahour', "")
deltaday = ""
if f.getfirst('deltaday', ""):
    deltaday = f.getfirst('deltaday', "")
exect = ""
if f.getfirst('exec', ""):
    exect = f.getfirst('exec', "")
if exect == "schedule":
    mode = "schedule"
    getRecDate()
elif exect == "yes":
    mode = "yes"
elif re.search('edit:', exect):
    mode = "edit"
elif re.search('edit-exec:', exect):
    mode = "edit-exec"
elif exect == "change":
    mode = "edit-rec10"
elif exect == "del":
    mode = "del"
elif exect == "iepg-add":
    mode = "iepg-add"
elif exect == "iepg-show":
    mode = "iepg-show"
elif exect == "iepg-add_yes":
    mode = "iepg-add-yes"
elif exect == "iepg-del":
    mode = "iepg-del"
htmdate = mode_normal()
htmdate = htmdate.replace("<!--text_for_replace_chtxt_input//-->", getchtxt())
htmdate = htmdate.replace("<!--btime-value//-->", btime)
htmdate = htmdate.replace("<!--etime-value//-->", etime)
htmdate = htmdate.replace("<!--type-value//-->", type)
htmdate = htmdate.replace("<!--ch-value//-->", chtxt)
htmdate = htmdate.replace("<!--title-value//-->", title)
htmdate = htmdate.replace("<!--size-value//-->", size)
htmdate = htmdate.replace("<!--opts-value//-->", opts)
#ここから曜日検索の設定
if f.getfirst('type') == "keyday":
    rett = ""
    dayt = f.getfirst('day_Mon')
    if dayt:
        rett = rett + reserv_recday(title, chtxt, btime, etime, deltahour, opts, deltaday, dayt)
    dayt = f.getfirst('day_Tue')
    if dayt:
        rett = rett + reserv_recday(title, chtxt, btime, etime, deltahour, opts, deltaday, dayt)
    dayt = f.getfirst('day_Wed')
    if dayt:
        rett = rett + reserv_recday(title, chtxt, btime, etime, deltahour, opts, deltaday, dayt)
    dayt = f.getfirst('day_Thu')
    if dayt:
        rett = rett + reserv_recday(title, chtxt, btime, etime, deltahour, opts, deltaday, dayt)
    dayt = f.getfirst('day_Fri')
    if dayt:
        rett = rett + reserv_recday(title, chtxt, btime, etime, deltahour, opts, deltaday, dayt)
    dayt = f.getfirst('day_Sat')
    if dayt:
        rett = rett + reserv_recday(title, chtxt, btime, etime, deltahour, opts, deltaday, dayt)
    dayt = f.getfirst('day_Sun')
    if dayt:
        rett = rett + reserv_recday(title, chtxt, btime, etime, deltahour, opts, deltaday, dayt)
    if rett == "":
        htmdate = mode_recfin()
    else:
        htmdate = mode_recover()
    chtxt = ""
    exect = ""


if mode == "schedule":
    htmdate = mode_schedule()
elif mode == "edit":
    htmdate = mode_edit()
elif mode == "iepg-add":
    htmdate = mode_iepg_add(station_name)
elif mode == "iepg-add-yes":
    try:
        database.new_iepg()
    except:
        ""
    if f.getfirst('iepg_station') and f.getfirst('iepg_chtxt'):
        database.add_iepg(f.getfirst('iepg_station'), f.getfirst('iepg_chtxt'))
    htmdate = mode_iepg_fin()
elif mode == "iepg-show":
    getiEPGDate()
    htmdate = mode_iepg_show()
elif mode == "iepg-del":
    s = f.getfirst('iepgdelnum')
    htmdate = ""
    #try:
    for st in s.split(","):
        if st != "":
            database.del_by_id_iepg(st)
    htmdate = mode_iepg_del()
    #except:
    #    htmdate=mode_iepg_del_miss()
elif mode == "edit-rec10":
    s = f.getfirst('tasknum')
    s.replace(" ", "")
    htmdate = mode_edit_rec10web(s.split(",")[0])
elif mode == "del":
    s = f.getfirst('tasknum')
    s.replace(" ", "")
    ss = s.split(",")
    for st in ss:
        if st != "":
            database.del_by_id_timeline(st)
    htmdate = mode_del()
elif mode == "edit-exec":
    if (chtxt != "")and(title != "")and(btime != "")and(etime != "")and(opts != ""):
        editnum = exect.replace("edit-exec:", "")
        restxt = change_reserv(editnum, type, title, chtxt, btime, etime, deltahour, opts, deltaday)
        if restxt == "":
            htmdate = mode_recfin()
        elif restxt == "over":
            htmdate = mode_recover()
        else:
            htmdate = mode_recfin()
    exect = ""
elif mode == "yes":
    if (chtxt != "")and(title != "")and(btime != "")and(etime != "")and(opts != ""):
        restxt = reserv(type, title, chtxt, btime, etime, deltahour, opts, deltaday)
        if restxt == "":
            htmdate = mode_recfin()
        elif restxt == "over":
            htmdate = mode_recover()
        else:
            htmdate = mode_recfin()
print "Content-Type: text/html"
print htmdate.encode('utf-8')
