#!/usr/bin/python
# coding: UTF-8
# Rec10 TS Recording Tools
# Copyright (C) 2009 Yukikaze
#import sys
#import os
import xml.parsers.expat
import sqlite3
#import xml.sax as sax
#from xml.sax.saxutils import DefaultHandler
flags={}
lastflag=""
xmldate={}
db=""
bctype=""
def xml2db(xmlpath,dbpath,bctypetemp):#bctypeは放送種別で'TE'(地デジ)BS,CSがある。地デジの場合は te数字 が入る
    global db,bctype
    bctype=bctypetemp
    #print path
    createDB(dbpath)
    #db.execute('drop table tv')
    #db.execute('drop table ch')

    p=xml.parsers.expat.ParserCreate()
    p.buffer_text=True
    p.StartElementHandler=start_element
    p.EndElementHandler=end_element
    p.CharacterDataHandler=char_data
    parseDocument(p,xmlpath)

def createDB(path):
    global db,bctype,fpath
    fpath=path
    db=sqlite3.connect(fpath)
    print fpath
    try:
        db.execute("delete from tv where bctype = \'"+bctype+"\'")
    except:
        test=""
    try:
        db.execute("delete from ch where bctype = \'"+bctype+"\'")
    except:
        test=""
    try:
        db.execute('create table tv (bctype TEXT,channel TEXT NOT NULL,start TEXT,stop  TEXT,title TEXT,desc  TEXT)')
    except:
        test=""
    try:
        db.execute('create table ch (bctype TEXT,channel TEXT NOT NULL,display TEXT)')
    except:
        test=""
    #db.commit()
    #db.close()
    #return db
def writetvDB(datetv):#tvdateは(放送種別,チャンネル,start,stop,title,desc)の形式
    global db
    #db=sqlite3.connect(fpath)
    #print datetv
    db.execute('insert into tv values '+datetv)
    #db.commit
    #return db
    #db.commit()
    #db.close()
def writechDB(datech):#tvdateは(チャンネル,display)の形式
    global db
    #db=sqlite3.connect(fpath)
    #print datech
    db.execute('insert into ch values '+datech)
    #db.commit
    #return db
    #db.commit()
    #db.close()
def parseDocument(p,xmlfile):
    f=open(xmlfile,'r')
    p.ParseFile(f)
    f.close()
def start_element(name,attrs):
    global flags,lastflag,xmldate
    flags[name]=1
    lastflag=name
    for (key,val) in attrs.iteritems():
        xmldate[name+":"+key]=val
def end_element(name):
    global flags,lastflag,xmldate,db
    if flags[name]==1: 
        if name=="channel":
            xmld="(\'"+bctype+"\',\'"+xmldate['channel:id']+"\',\'"+xmldate['display-name']+"\')"
            xmld=unicode(xmld)
            writechDB(xmld)
            xmldate['channel:id']=""
            xmldate['display-name']=""
            #xmldate={}
            #print xmld
        elif name=="programme":
            
            xmld="(\'"+bctype+"\',\'"+xmldate['programme:channel']+"\',\'"+xmldate['programme:start'].replace(" +0900","")+"\',\'"+xmldate['programme:stop'].replace(" +0900","")+"\',\'"+xmldate['title'].replace(",","-")+"\',\'"+xmldate['desc']+"\')"
            xmld=unicode(xmld)
            writetvDB(xmld)
            #print xmld
            xmldate['title']=""
            xmldate['desc']=""
            #xmldate[]
        if name=="tv":
            """
            r=db.execute("SELECT * FROM tv")
            for row in r:
                print row
            """
            db.commit()
            db.close()
    flags[name]=0
def char_data(date):
    global flags,lastflag,xmldate
    #string=str(date)
    date=date.replace("\n","")
    date=date.replace(" ","")
    date=date.replace("(","[")
    date=date.replace(")","]")
    date=date.replace("（","[")
    date=date.replace("）","]")
    date=date.replace("\"","")
    date=date.replace("\'","")
    date=date.encode('utf-8')
    #date=string
    if xmldate.has_key(lastflag):
        if xmldate[lastflag]!=date:
            xmldate[lastflag]+=date
    else:
        xmldate[lastflag]=date
    #if lastflag=='category':
    #print date
    #print xmldate




