#!/usr/bin/python
# coding: UTF-8
# Rec10 TS Recording Tools
# Copyright (C) 2009-2012 Yukikaze
import datetime
import os
import os.path
import glob
import time
import traceback

import configreader
import recdblist
import recdb
tmppath = configreader.getConfPath("tmp")+"/"
if not os.path.exists(tmppath):
    os.mkdir(tmppath)
def writeRecQue(parentpath,chtxt,title,opts):
    outputpath=os.path.join(parentpath,title+".recq")
    tmpoppath=os.path.join(tmppath,title+".recq")
    f=open(outputpath,"w")
    optt=opts
    str="99"+","+datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")+","+configreader.getConfEnv("iff")+","+chtxt+","+title+","+optt
    f.write(str.encode('utf-8'))
    f.close()
    if not os.path.exists(outputpath):
        if os.path.exists(tmpoppath):
            os.remove(tmpoppath)
        f2=open(tmpoppath,"w")
        f2.write(str.encode('utf-8'))
        f2.close()
        try:
            os.chmod(tmpoppath)
        except:
            ""
        shutil.copy(tmpoppath,outputpath)
        os.remove(tmpoppath)
def readRecQue(recquepath):
    f=open(recquepath,"r")
    line = unicode(f.readline(),'utf-8')
    title=""
    opts=""
    chtxt=""
    while line:
        linec=line.split(",")
        if len(linec)>3:
            if linec[0]=="99":
                title=linec[4]
                opts=linec[5]
                chtxt=linec[2]+u"_"+linec[3]
                break
        line = unicode(f.readline(),'utf-8')
    dbkey=""
    if opts.find("R")>-1:
        dbkey=recdblist.REC_TS_DECODE_QUE
        opts=opts.replace("R","")
    elif opts.find("D")>-1:
        dbkey=recdblist.REC_ENCODE_QUE
        opts=opts.replace("D","")
    elif opts.find("E")>-1:
        dbkey=""
        opts=opts.replace("E","")
    
    bt=datetime.datetime.now()+datetime.timedelta(minutes=5)
    et=bt+datetime.timedelta(minutes=30)
    btime=bt.strftime("%Y-%m-%d %H:%M:%S")
    etime=et.strftime("%Y-%m-%d %H:%M:%S")
    if len(dbkey)>2:
        recdb.reserveReckey(dbkey, title, chtxt, btime, etime, opts)
def searchRecQue(folderpath):
    for file in glob.glob(os.path.join(folderpath,"*.recq")):
        dtime = time.time()-os.path.getmtime(file)
        dtime = int(dtime)
        if dtime > 300:
            try:
                readRecQue(os.path.join(folderpath, file))
                os.remove(os.path.join(folderpath, file))
            except Exception, inst:
                recdblist.addCommonlogEX("Error", "searchRecQue(recque.py)", str(type(inst)), str(inst)+traceback.format_exc(),log_level=200)
                
