#!/usr/bin/python
# coding: UTF-8
# Rec10 TS Recording Tools
# Copyright (C) 2009 Yukikaze
import os
import sqlite3
import recdb
dbpath=str(os.path.dirname(os.path.abspath(__file__)))+"/"+"ch.db"
db=sqlite3.connect(dbpath)

"""
task names
"""
global REC_RESERVE
global REC_FINAL_RESERVE
global REC_END
global REC_ENCODE_GRID
global REC_ENCODE_LOCAL
global REC_ENCODE_QUE
global REC_MIXING_SOUND
global REC_MISS_ENCODE
global REC_KEYWORD
global REC_KEYWORD_EVERY_SOME_DAYS
global REC_FIN_DECODE
global REC_FIN_LOCAL
global REC_MISS_DECODE
global REC_TS_DECODING
global REC_TS_RECORDING
REC_RESERVE="res"
REC_FINAL_RESERVE="rec"
REC_END="end"
REC_ENCODE_GRID="grid"
REC_ENCODE_LOCAL="local"
REC_ENCODE_QUE="ts2avi"
REC_MIXING_SOUND="mixsound"
REC_MISS_ENCODE="miss"
REC_KEYWORD="key"
REC_KEYWORD_EVERY_SOME_DAYS="keyevery"
REC_FIN_DECODE="tsfin"
REC_FIN_LOCAL="fin_local"
REC_MISS_DECODE="tsmiss"
REC_TS_DECODING="tsdecoding"
REC_TS_RECORDING="tsrecording"

try:
    db.execute('create table rectime (type TEXT,chtxt TEXT,title TEXT,btime TEXT,etime TEXT,deltatime TEXT,deltaday TEXT,opt TEXT,id INTEGER PRIMARY KEY,UNIQUE(type,chtxt,title,btime,deltaday))')
except:
    #print "テーブル作成に失敗しました"
    db.commit()
    db.close()
def recreserv(title,chtxt,btime,etime,opt):#optにはa(アニメ)d(副音声)v(xvid)
    rec_reckey("res",title,chtxt,btime,etime,opt)
def keyreserv(keyword,chtxt,btime,etime,deltatime,opt):
    db=sqlite3.connect(dbpath)
    recline="\""+recdb.REC_KEYWORD+"\",\""+chtxt+"\",\""+keyword+"\",datetime(\""+btime+"\"),datetime(\""+etime+"\"),\""+deltatime+"\",\""+opt+"\""
    db.execute('insert into rectime ("type","chtxt","title","btime","etime","deltatime","opt") values ('+recline+')')
    db.commit()
    db.close()
def everyreserv(keyword,chtxt,btime,etime,deltatime,opt,deltaday):
    db=sqlite3.connect(dbpath)
    recline="\""+recdb.REC_KEYWORD_EVERY_SOME_DAYS+"\",\""+chtxt+"\",\""+keyword+"\",datetime(\""+btime+"\"),datetime(\""+etime+"\"),\""+deltatime+"\",\""+opt+"\",\""+deltaday+"\""
    db.execute('insert into rectime ("type","chtxt","title","btime","etime","deltatime","opt","deltaday") values ('+recline+')')
    db.commit()
    db.close()
def lastrecreserv(title,chtxt,btime,etime,opt):#optにはa(アニメ)d(副音声)v(xvid)##btimeなどは2006-07-17 13:25:23の形
    """
    Caution this is old function and you should not use it.
    Please use rec_reckey(recdb.REC_FINAL_RESERVE,title,chtxt,btime,etime,opt) instead of lastrecreserv(title,chtxt,btime,etime,opt)
    """
    rec_reckey(recdb.REC_FINAL_RESERVE,title,chtxt,btime,etime,opt)
def misrecwrite(title,chtxt,btime,etime,opt):

    """
    Caution this is old function and you should not use it.
    Please use rec_reckey(recdb.REC_MISS_ENCODE,title,chtxt,btime,etime,opt) instead.
    """
    rec_reckey(recdb.REC_MISS_ENCODE,title,chtxt,btime,etime,opt)
def recend(title,chtxt,btime,etime,opt):#optにはa(アニメ)d(副音声)v(xvid)
    """
    Caution this is old function and you should not use it.
    Please use rec_reckey(recdb.REC_END,title,chtxt,btime,etime,opt) instead.
    """
    rec_reckey(recdb.REC_END,title,chtxt,btime,etime,opt)
def rec_reckey(type,title,chtxt,btime,etime,opt):
    db=sqlite3.connect(dbpath)
    recline="\""+type+"\",\""+chtxt+"\",\""+title+"\",datetime(\""+btime+"\"),datetime(\""+etime+"\"),\""+opt+"\""
    db.execute('insert into rectime ("type","chtxt","title","btime","etime","opt") values ('+recline+')')
    db.commit()
    db.close()
def delrec(title,chtxt,btime):
    """
    Caution this is old function and you should not use it.
    Please use del_reckey(recdb.REC_RESERVE,title,chtxt,btime) instead.
    """
    del_reckey(recdb.REC_RESERVE,title,chtxt,btime)
def delkey(keyword,chtxt,btime,deltatime):
    """
    Caution this is old function and you should not use it.
    Please use del_reckey(recdb.REC_FINAL_RESERVE,keyword,chtxt,btime) instead.
    """
    del_reckey(recdb.REC_KEYWORD,keyword,chtxt,btime)
def dellastrec(title,chtxt,btime):
    """
    Caution this is old function and you should not use it.
    Please use del_reckey(recdb.REC_FINAL_RESERVE,title,chtxt,btime) instead.
    """
    del_reckey(recdb.REC_FINAL_RESERVE,title,chtxt,btime)
def delevery(keyword,chtxt,btime,deltatime,deltaday):
    """
    Caution this is old function and you should not use it.
    Please use del_reckey(recdb.REC_FINAL_RESERVE,keyword,chtxt,btime) instead.
    """
    del_reckey(recdb.REC_KEYWORD_EVERY_SOME_DAYS,keyword,chtxt,btime)
def delend(title,chtxt,btime):
    """
    Caution this is old function and you should not use it.
    Please use del_reckey(recdb.REC_END,title,chtxt,btime) instead.
    """
    del_reckey(recdb.REC_END,title,chtxt,btime)
def deltitle(key):
    db=sqlite3.connect(dbpath)
    i=0
    for title in db.execute("SELECT title FROM rectime WHERE title like \"%"+key+"%\""):
        i=i+1
    if i==1:
        db.execute("delete from rectime where title like \'%"+key+"%\'")
    db.commit()
    db.close()
def del_reckey(type,title,chtxt,btime):
    db=sqlite3.connect(dbpath)
    db.execute("delete from rectime where type = \'"+type+"\' AND title = \'"+title+"\' AND chtxt = \'"+chtxt+"\' AND btime = datetime(\""+btime+"\")")
    db.commit()
    db.close()
def getnow(dhour):
    db=sqlite3.connect(dbpath)
    recdatum=[]
    for typet, chtxt, title, btime, etime, deltatime ,deltaday ,opt in db.execute("SELECT type, chtxt, title, DATETIME(btime), DATETIME(etime), deltatime ,deltaday ,opt FROM rectime WHERE btime < datetime(\'now\',\'localtime\',\'+"+dhour+" hours\') AND btime >datetime(\'now\',\'localtime\',\'-"+dhour+" hours\')"):
        ret={}
        ret['type']=typet
        ret['chtxt']=chtxt
        ret['title']=title.encode('utf-8')
        ret['btime']=btime
        ret['etime']=etime
        ret['opt']=opt
        if deltatime==None or deltatime=="":
            deltatime="3"
        if deltaday==None or deltaday=="":
            deltaday="7"
        if typet=='key':
            ret['deltatime']=deltatime
        elif typet=='keyevery':
            ret['deltatime']=deltatime
            ret['deltaday']=deltaday
        recdatum.append(ret)
    db.commit()
    db.close()
    return recdatum
def countRecNow(dhour):
    d=getnow(dhour)
    ret=0
    for i in d:
        t=i['type']
        if t=="key" or t=="keyevery" or t=="rec" or t=="ret":
            ret=ret+1
    return ret
def delete_old(dhour):
    """
    delete keys except recdb.REC_MISS_ENCODE and recdb.REC_KEYWORD_EVERY_SOME_DAYS before dhour hours from now.
    """
    db=sqlite3.connect(dbpath)
    db.execute("DELETE FROM rectime WHERE NOT ( type = \""+recdb.REC_MISS_ENCODE+"\" OR type = \""+recdb.REC_KEYWORD_EVERY_SOME_DAYS+"\" ) AND btime < datetime(\'now\',\'localtime\',\'-"+dhour+" hours\')")
    db.commit()
    db.close()
def getall():
    db=sqlite3.connect(dbpath)
    recdata=[]
    for typet, chtxt, title, btime, etime, deltatime ,deltaday ,opt in db.execute("SELECT type, chtxt, title, btime, etime, deltatime ,deltaday ,opt FROM rectime"):
        ret={}
        ret['type']=typet
        ret['chtxt']=chtxt
        ret['title']=title.encode('utf-8')
        ret['btime']=btime
        ret['etime']=etime
        ret['opt']=opt
        if deltatime==None:
            deltatime="3"
        if deltaday==None:
            deltaday="7"
        if typet=='key':
            ret['deltatime']=deltatime
        elif typet=='keyevery':
            ret['deltatime']=deltatime
            ret['deltaday']=deltaday
        recdata.append(ret)
    db.close()
    return recdata
