#!/usr/bin/python
# coding: UTF-8
# Rec10 TS Recording Tools
# Copyright (C) 2009 Yukikaze
import sys
import time
import os
import datetime
import epgdb
import configreader
import ts2x264
import tv2avi
import recdb
import chdb
import status
import re
recpath=configreader.getpath('recpath')
path=str(os.path.dirname(os.path.abspath(__file__)))+"/"
def task():
    """
    数分毎に実行されるタスク処理
    予定によって子プロセスを生成し処理する。
    """
    recdb.delete_old("6")
    tasks=recdb.getnow("1")
    if len(tasks)==0:
        update=chdb.update()
        print "番組表更新処理"
        print update
        if len(update)>0:
            print "番組表を更新"
            print update
            pid=os.fork()
            if pid>0:#親プロセスの場合
                ""
            else:#子プロセスの場合　アップデートを行って終了
                for bctype in update:
                    time.sleep(1)
                    print bctype
                    epgdb.updatebc(bctype)
                sys.exit(0)

    for task in tasks:
        try:
            chtxt=task['chtxt']
        except:
            chtxt=""
        try:
            title=task['title']
        except:
            title=""
        try:
            btime=task['btime']
            bt=datetime.datetime.strptime(btime,"%Y-%m-%d %H:%M:%S")
        except:
            btime=""
            bt=datetime.datetime.strptime("2009-01-01 00:00:00","%Y-%m-%d %H:%M:%S")
        try:
            etime=task['etime']
            et=datetime.datetime.strptime(etime,"%Y-%m-%d %H:%M:%S")
        except:
            etime=""
            et=datetime.datetime.strptime("2009-01-01 00:00:00","%Y-%m-%d %H:%M:%S")
        try:
            opt=task['opt']
        except:
            opt=""
        tnow=datetime.datetime.now()
        dtt=bt-tnow#
        dt=dtt.days*24*60*60+dtt.seconds
        
        if task["type"]==recdb.REC_RESERVE:#"res,"+chtxt+","+title+","+btime+","+etime+","+opt
            if dt<58*60:
                recdb.del_reckey(recdb.REC_RESERVE, title, chtxt, btime)
                recdb.rec_reckey(recdb.REC_FINAL_RESERVE, title, chtxt, btime, etime, opt)

        elif task["type"]==recdb.REC_KEYWORD:#"key,"+chtxt+","+keyword+","+btime+","+deltatime+","+opt
            deltatime=task['deltatime']
            if dt<30*60:
                recdatum=epgdb.searchtime(title,btime,deltatime)
                if len(recdatum)>0:
                    recdb.del_reckey(recdb.REC_KEYWORD, title, chtxt, btime)
                    for recdata in recdatum:
                        recds=recdata.split(",")
                        chtxt=recds[0]
                        title=recds[1]
                        btime=recds[2]
                        etime=recds[3]
                        bt=datetime.datetime.strptime(btime,"%Y-%m-%d %H:%M:%S")
                        et=datetime.datetime.strptime(etime,"%Y-%m-%d %H:%M:%S")
                        btime=bt.strftime("%Y-%m-%d %H:%M:%S")
                        etime=et.strftime("%Y-%m-%d %H:%M:%S")
                        recdb.rec_reckey(recdb.REC_FINAL_RESERVE, title, chtxt, btime, etime, opt)
                else :
                    print "nothing match"

        elif task["type"]==recdb.REC_KEYWORD_EVERY_SOME_DAYS:#"keyevery,"+chtxt+","+keyword+","+btime+","+deltatime+","+opt+","+deltaday
            deltatime=task['deltatime']
            deltaday=task['deltaday']
            dd=datetime.timedelta(days=int(deltaday))
            if dtt.days<0:
                recdb.del_reckey(recdb.REC_KEYWORD_EVERY_SOME_DAYS, title, chtxt, btime)
                bt=bt+dd
                et=et+dd
                btxt=bt.strftime("%Y-%m-%d %H:%M:%S")
                etxt=et.strftime("%Y-%m-%d %H:%M:%S")
                recdb.everyreserv(title,chtxt,btxt,etxt,deltatime,opt,deltaday)
            elif dt<30*60*60:
                recdb.keyreserv(title,chtxt,btime,etime,deltatime,opt)
                recdb.del_reckey(recdb.REC_KEYWORD_EVERY_SOME_DAYS, title, chtxt, btime)
                bt=bt+dd
                et=et+dd
                btxt=bt.strftime("%Y-%m-%d %H:%M:%S")
                etxt=et.strftime("%Y-%m-%d %H:%M:%S")
                recdb.everyreserv(title,chtxt,btxt,etxt,deltatime,opt,deltaday)

        elif task["type"]==recdb.REC_FINAL_RESERVE:#"rec,"+chtxt+","+title+","+btime+","+etime+","+opt
            print dt
            if dt<6*60:
                recdb.del_reckey(recdb.REC_FINAL_RESERVE, title, chtxt, btime)
                recdb.rec_reckey(recdb.REC_TS_DECODING, title, chtxt, btime, etime, opt)
                print "録画開始"
                pid=os.fork()
                if pid>0:#親プロセスの場合
                    ""
                else:
                    #print title
                    tv2avi.timetv2avi(recpath+"/"+title+".avi",chtxt,btime,etime,opt)
                    if not os.access(recpath+"/"+title+".ts", os.F_OK):
                        recdb.del_reckey(recdb.REC_TS_DECODING, title, chtxt, btime)
                        recdb.rec_reckey(recdb.REC_MISS_DECODE, title, chtxt, btime, etime, opt)
                    else:
                        recdb.del_reckey(recdb.REC_TS_DECODING, title, chtxt, btime)
                        tnow=datetime.datetime.now()
                        bt=datetime.datetime.strptime(btime,"%Y-%m-%d %H:%M:%S")
                        et=datetime.datetime.strptime(etime,"%Y-%m-%d %H:%M:%S")
                        dt=tnow-bt
                        bt=tnow+datetime.timedelta(seconds=600)
                        et=et+dt+datetime.timedelta(seconds=600)
                        btime=bt.strftime("%Y-%m-%d %H:%M:%S")
                        etime=et.strftime("%Y-%m-%d %H:%M:%S")
                        recdb.rec_reckey(recdb.REC_ENCODE_QUE,title,chtxt,btime,etime,opt)
                        recdb.rec_reckey(recdb.REC_FIN_DECODE,title,chtxt,btime,etime,opt)
                    sys.exit(0)

        elif task["type"]==recdb.REC_ENCODE_QUE:
            if dt<10*60:
                if status.getEncoding()<2:
                    pid=os.fork()
                    if pid>0:#親プロセスの場合
                            ""
                    else:
                        pin=recpath+"/"+title+".ts"
                        if re.search("d",opt):
                            pin=recpath+"/"+title+"sa.avi"
                        if re.search("5",opt):
                            pin=recpath+"/"+title+"sa.avi"
                        pout=recpath+"/"+title+".avi"
                        print pin+":"+pout+":"+opt
                        recdb.del_reckey(recdb.REC_ENCODE_QUE,title,chtxt,btime)
                        recdb.rec_reckey(recdb.REC_ENCODE_LOCAL, title, chtxt, btime, etime, opt)
                        ts2x264.ts2x264(pin, pout, opt)
                        sys.exit(0)
                else:
                    recdb.del_reckey(recdb.REC_ENCODE_QUE,title,chtxt,btime)
                    bt=bt+datetime.timedelta(seconds=600)
                    et=et+datetime.timedelta(seconds=600)
                    btime=bt.strftime("%Y-%m-%d %H:%M:%S")
                    etime=et.strftime("%Y-%m-%d %H:%M:%S")
                    recdb.rec_reckey(recdb.REC_ENCODE_QUE,title,chtxt,btime,etime,opt)
