#!/usr/bin/python
# coding: UTF-8
# Rec10 TS Recording Tools
# Copyright (C) 2009-2011 Yukikaze
#import sys # モジュール属性 argv を取得するため
import os
import re
import time
import commands

import chdb
import configreader
import tv2ts
import recdblist

def writeEpgXML(pout, ch):
    """
    tsを取得してepgの入ったxmlとして書き出す
    """
    timet = "90"
    if re.search(u'CS', ch):
        timet = "180"
    elif len(ch)>2:
        timet = "240"
    writeEpgXMLTime(pout, ch ,timet)
def writeLogoEpgXML(pout, ch):
    """
    tsを取得してepgの入ったxmlとして書き出す
    """
    timet = "600"
    if re.search(u'CS', ch):
        timet = "10"
    elif len(ch)>2:
        timet = "1200"
    writeEpgXMLTime(pout, ch ,timet,islogo=1)
def writeEpgXMLTime(pout, ch ,times,islogo=0):
    """
    指定された時間分tsを取得してepgの入ったxmlとして書き出す
    """
    if islogo==0:
        recdblist.addCommonlogEX(u"通常","write_time(ts2epg.py)",u"Ts-EPG XML書き出し処理開始" ,u"CH:"+ch,log_level=500)
    elif islogo==1:
        recdblist.addCommonlogEX(u"通常","write_time(ts2epg.py)",u"Ts-EPG LOGO : XML書き出し処理開始" ,u"CH:"+ch,log_level=500)
    timet = times
    if re.search(u'CS', ch):
        mode = "/CS"
    elif len(ch)>2:
        mode = "/BS"
    else:
        mode = str(chdb.searchCHFromBctype(u'te' + ch)['ch'])
    epgdump = configreader.getConfPath("epgdump")
    if os.access(pout + ".ts", os.F_OK):
        os.remove(pout + ".ts")
    time.sleep(10)
    tv2ts.tv2b25ts(pout+ ".ts", ch, times,"0")
    logoopt=""
    if islogo==1:
        logoopt="/LOGO "
    os.chmod(pout+".ts",0755)
    exe = "export LANG=ja_JP.UTF-8 && nice -n 15 " + epgdump + " " +logoopt+ mode + " " + pout + ".ts " + pout
    recdblist.printutf8(exe)
    recdblist.addCommonlogEX(u"通常", "write_time(ts2epg.py) "+str(ch), exe,"",log_level=500)
    unicode(commands.getoutput(exe),'utf-8','ignore')
    time.sleep(10)
    if os.path.exists(pout+".ts"):
        os.remove(pout+ ".ts")

