#!/usr/bin/python
# coding: UTF-8
# Rec10 TS Recording Tools
# Copyright (C) 2009-2012 Yukikaze

import sys
import subprocess
import time
import os
import os.path
import signal

import configreader
import recdblist
#
#CHの定義は
#1-64 地デジ
#BS1,BS3...BS23 BS放送
#CS2,CS4...CS24 CS放送

tmppath = configreader.getConfPath("tmp")+"/"
def channel2freq(channel):##freqを返す
    freq=""
    if channel[0:2].upper() != "CS" and channel[0:2].upper() != "BS":
        ch=int(channel)
        if ch<65:#TE 13ch 473_142857
            freq=str(473+(ch-13)*6)+u"142857"
    elif channel[0:2].upper() == "CS":#CS2,CS4,CS6...CS24
        ch=int(channel.upper().replace("CS",""))
        #freq = 12291000 + (CH_IDX - 2) * 40000 / 2 - 10678000;
        freq=str((ch-2)*40000/2+1613000)
    elif channel[0:2].upper() == "BS":#BS1,BS3,BS5...BS23
        ch=int(channel.upper().replace("BS",""))
        freq=str((ch-1)*38360/2+1049480)
    return freq
def testTune(adapter,channel):
    my_env=recdblist.getEnv()
    tunecmd=configreader.getConfDVB("DVBtune")+u" "+adapter+u" "+channel2freq(channel)
    #p1=subprocess.Popen(tunecmd,shell=True)
    p1=subprocess.Popen([configreader.getConfDVB("DVBtune"),adapter,channel2freq(channel)],env=my_env,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    time.sleep(0.2)
    try:
        os.kill(p1.pid,signal.SIGKILL)
    except:
        ""
    if p1.communicate()[1].find("busy")>-1:
        try:
            p1.wait()
        except:
            ""
        return 0
    else:
        try:
            p1.wait()
        except:
            ""
        return 1
def getAdapter(channel):
    chl=[]
    if channel[0:2].upper()=="BS" or channel[0:2].upper()=="CS":
        chl=configreader.getConfDVB("DVBBSCS").split(",")
    elif int(channel)<65:
        chl=configreader.getConfDVB("DVBTE").split(",")
    chlr=[]
    for i in chl:
        chlr.append(int(i))
    return chlr
def getActiveAdapter(channel):
    for i in getAdapter(channel):
        rt=testTune(str(i),channel)
        if rt==1:
            return str(i)
def record(channel,tsid,out,timelength,decode=0):
    if not os.path.exists(tmppath+u"rec.sh"):
        ft=open(tmppath+u"rec.sh","w")
        ft.write(u"#!/bin/bash\n/bin/cat $1 > \"$2\"")
        ft.close()
        os.system(u"chmod +x "+tmppath+u"rec.sh")
    adapt=getActiveAdapter(channel)
    my_env=recdblist.getEnv()
    if adapt!=None:
        tunecmd=configreader.getConfDVB("DVBtune")+u" "+adapt+u" "+channel2freq(channel)+u" "+tsid+u" "+timelength+u" "+out
        #reccmd=u"/bin/cat \""+configreader.getConfDVB("DVBadapter")+adapt+u"/dvr0\" > \""+out+u"\""
        #if decode==1:
        #    reccmd=configreader.getConfPath("b25")+u" -v 0 \""+configreader.getConfDVB("DVBadapter")+adapt+u"/dvr0\" \""+out+"\""
        recdblist.addLog(out, tunecmd, "record(DVB)",100)
        p1=subprocess.Popen([configreader.getConfDVB("DVBtune"),adapt,channel2freq(channel),tsid,timelength,out],env=my_env)
        #time.sleep(0.2)
        #if decode==1:
        #    p2=subprocess.Popen([configreader.getConfPath("b25"),u"-v 0",u"\""+configreader.getConfDVB("DVBadapter")+adapt+"/dvr0\"","\""+out+"\""],preexec_fn=os.setsid,env=my_env,bufsize=-1)
        #else:
        #    p2=subprocess.Popen([tmppath+u"rec.sh",configreader.getConfDVB("DVBadapter")+adapt+"/dvr0",out],preexec_fn=os.setsid,env=my_env,bufsize=-1)
            #p2=subprocess.Popen(reccmd,shell=True,preexec_fn=os.setsid,env=my_env,bufsize=-1)
        #time.sleep(float(timelength))
        #os.killpg(p2.pid,signal.SIGKILL)
        #p2.wait()
        #os.kill(p1.pid,signal.SIGKILL)
        p1.wait()
    else:
        recdblist.printutf8ex(u"tuner busy",100,100)
def useDVB():
    try:
        if int(configreader.getConfDVB("useDVB").replace(" ",""))==1:
            return 1
        else:
            return 0
    except:
        return 0