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

__author__="yukikaze"
__date__ ="$2009/09/14 17:38:25$"

import glob
import n_gram
import os
import os.path
import re
import time
import optparse
import sys
import shutil

import configreader
recordedpath=configreader.getpath("recorded")
recpath=configreader.getpath("recpath")
def search_b25(path):
    """
    録画フォルダを検索し、各QUEの実行状況を表示する
    """
    b25list = glob.glob(path + "/*.b25")
    for b25f in b25list:
        ##b25f is title.ts.b25  avi is title.avi
        dir = os.path.split(b25f)[0]
        title = os.path.split(b25f)[1]
        title = title.replace(".ts.b25", "")
        avipath = os.path.join(dir, title + ".avi")
        mp4path = os.path.join(dir, title + ".mp4")
        tspath = os.path.join(dir, title + ".ts")
        b25f = b25f.replace(".ts.b25", ".avi")
        mode = "ts"
        if os.path.isfile(tspath):##tsファイルが存在している
            dtime = time.time()-os.path.getmtime(tspath)
            dtime = int(dtime)
            if dtime > 120:
                if os.path.getsize(tspath) > 1 * 1000 * 1000:##最終更新から22分以上経過かつ1MB以上
                    mode = "avi"
                else:
                    mode = "tsmiss"
            else:
                mode = "ts"
        if os.path.isfile(mp4path):##tsファイルが存在している
            dtime = time.time()-os.path.getmtime(mkvpath)
            dtime = int(dtime)
            if dtime > 120:
                if os.path.getsize(avipath) > 1 * 1000 * 1000:##最終更新から22分以上経過かつ1MB以上
                    mode = "fin"
                else:
                    mode = "avimiss"
            else:
                mode = "avi"
        print title + ":" + mode
def search_avi(temppath,recpath):
    """
    録画一時フォルダ内のaviファイルを検索
    """
    avilist = glob.glob(temppath + "/*.avi")
    ret=[]
    for avif in avilist:
        ##b25f is title.ts.b25  avi is title.avi
        dir = os.path.split(avif)[0]
        title = os.path.split(avif)[1]
        title = title.replace(".avi", "")
        avipath = os.path.join(dir, title + ".avi")
        dtime = time.time()-os.path.getmtime(avipath)
        dtime = int(dtime)
        if dtime > 300:
            if veryfySize(avipath):
                ret.append(title)
    return ret
def search_mkv(temppath,recpath):
    """
    録画一時フォルダ内mkvファイルを検索
    """
    avilist = glob.glob(temppath + "/*.mkv")
    ret=[]
    for avif in avilist:
        ##b25f is title.ts.b25  avi is title.avi
        dir = os.path.split(avif)[0]
        title = os.path.split(avif)[1]
        title = title.replace(".mkv", "")
        avipath = os.path.join(dir, title + ".mkv")
        dtime = time.time()-os.path.getmtime(avipath)
        dtime = int(dtime)
        if dtime > 300:
            if veryfySize(avipath):
                ret.append(title)
    return ret
def search_mp4(temppath,recpath):
    """
    録画一時フォルダ内mp4ファイルを検索
    """
    avilist = glob.glob(temppath + "/*.mp4")
    ret=[]
    for avif in avilist:
        ##b25f is title.ts.b25  avi is title.avi
        dir = os.path.split(avif)[0]
        title = os.path.split(avif)[1]
        title = title.replace(".mp4", "")
        avipath = os.path.join(dir, title + ".mp4")
        dtime = time.time()-os.path.getmtime(avipath)
        dtime = int(dtime)
        if dtime > 300:
            if veryfySize(avipath):
                ret.append(title)
    return ret
def veryfySize(path):
    #vsize=[297,497,596,1196]#SD 30m 1h 1.5h 2h
    vsize=[245,275,295,591,830]
    vsize=vsize+[325,560,590,602,690,860]
    #vsize=vsize+[458,916]#HD 30m 1h
    #vsize=vsize+[381,895,447]
    ret = 0
    for size in vsize:
        if os.path.getsize(path)>(size-10)*1024*1024 and os.path.getsize(path)<(size+10)*1024*1024:
            ret=1
    return ret
def searchFolder(title,path):
    """
    titleにマッチするフォルダを探し出す。
    """
    folderpath=os.listdir(path)
    lfpath=[]
    ngram=[]
    for ft in folderpath:
        fullpath=os.path.join(path, ft)
        if os.path.isdir(fullpath):
            lfpath.append(fullpath)
            ftt=os.listdir(fullpath)
            if len(ftt)>0:
                for ft2 in ftt:
                    folderpath.append(os.path.join(fullpath, ft2))
        else:
            lfpath.append(fullpath)
    for dirp in lfpath:
        cmpp=""
        appp=""
        if os.path.isdir(dirp):
            cmpp=os.path.dirname(dirp)
            appp=dirp
        else:
            cmpp=os.path.basename(dirp)
            appp=os.path.dirname(dirp)
        p=n_gram.trigram(title.decode("utf-8"),cmpp.decode("utf-8"))
        if p>0:
            ngram.append((p,appp))
    ngram=list(set(ngram))
    ngram.sort()
    ngram.reverse()
    if len(ngram)>0:
        #print title + ngram[0][1] + " : "+str(ngram[0][0])
        if ngram[0][0]>400:
            return ngram[0][1]
        else:
            return ""
    else:
        return ""
def execMove(title,temppath,recpath):
    srcpath=os.path.join(temppath,title+".mp4")
    #desttitle=destName(title, temppath, recpath)
    
    sf=searchFolder(title, recpath)
    if sf!="":
        destpath=os.path.join(sf,destNameMP4(title, temppath, sf)+".mp4")
        #os.path.join(sf,desttitle+".mkv")
        #print srcpath
        #print destpath
        print "moving now.."
        print srcpath+" : "+destpath
        shutil.move(srcpath, destpath)
        #shutil.copy(srcpath, destpath)
        delpath=[os.path.join(temppath,title+".ts")]
        delpath.append(os.path.join(temppath,title+".avi"))
        delpath.append(os.path.join(temppath,title+".ts.b25"))
        delpath.append(os.path.join(temppath,title+".ts.tsmix"))
        delpath.append(os.path.join(temppath,title+".ts.log"))
        delpath.append(os.path.join(temppath,title+".sa.avi"))
        delpath.append(os.path.join(temppath,title+".sa.avi.log"))
        delpath.append(os.path.join(temppath,title+".log"))
        for dp in delpath:
            try:
                os.remove(dp)
                ""
            except:
                ""
def destName(title,temppath,recpath):
    """
    titleから移動先に作るべきファイル名を作り出す。
    """
    dstpath=os.path.join(recpath,title+".avi")
    srcpath=os.path.join(temppath,title+".avi")
    if os.path.exists(dstpath):
        gmtime=time.gmtime(os.path.getmtime(srcpath))
        times=time.strftime("%y%m%d",gmtime)
        title=title+"_"+times
    return title
def destNameMKV(title,temppath,recpath):
    """
    titleから移動先に作るべきファイル名を作り出す。
    """
    dstpath=os.path.join(recpath,title+".mkv")
    srcpath=os.path.join(temppath,title+".mkv")
    if os.path.exists(dstpath):
        gmtime=time.gmtime(os.path.getmtime(srcpath))
        times=time.strftime("%y%m%d",gmtime)
        title=title+"_"+times
    return title
def destNameMP4(title,temppath,recpath):
    """
    titleから移動先に作るべきファイル名を作り出す。
    """
    dstpath=os.path.join(recpath,title+".mp4")
    srcpath=os.path.join(temppath,title+".mp4")
    if os.path.exists(dstpath):
        gmtime=time.gmtime(os.path.getmtime(srcpath))
        times=time.strftime("%y%m%d",gmtime)
        title=title+"_"+times
    return title
def detName(path,title):
    """
    type A ---title#<number>
    type B ---title#<number>subtitle
    type C ---title subtitle
    type D ---title(without number)
    """
    #if re.match("#\d\s[0,10]\z|#[0-9]\s[0,10]\z", title)
    #    print "typeA"
    #elif re.match("#\d\s[0,10].|#[0-9]\s[0,10].", title)
    #    print "typeB"

def detNameType(title):
    """
    type A ---title#<number>
    type B ---title#<number>subtitle
    type C ---title subtitle
    type D ---title(without number)
    """
    print title
    #rA=re.compile(".+(?P<title>)#\d(?P<num>)\s[0,10]\z")
    rA=re.compile("(.+)#(\d*)\s*\Z")
    tA=rA.match(title)
    rB=re.compile("(.+)#(\d*)\s*(\D*)")
    tB=rB.match(title)
    if tA:
        print "typeA"
        print "title="+tA.group(1)
        print "num="+tA.group(2)
    elif tB:
        print "typeB"
        print "title="+tB.group(1)
        print "num="+tB.group(2)
        print "subtitle="+tB.group(3)
if __name__ == "__main__":
    usage="usage: %prog read -h"
    version="%prog 0.7.0beta1"
    parser=optparse.OptionParser(usage=usage,version=version)
    parser.add_option("-s","--search",action="store",type="string",dest="ltitle",default="",metavar="TITLE",help="test to search where the title should be contained(test for -e)")
    parser.add_option("-A","--Auto",action="store_true",dest="auto",default=False,help="auto classifying mode(not a test)")
    parser.add_option("-e","--exec",action="store",type="string",dest="etitle",default="",metavar="TITLE",help="exec move(not a test)")
    parser.add_option("-l","--list",action="store_true",dest="list",default=False,help="File listing mode(test for -a)")
    (opts,args)=parser.parse_args(sys.argv)
    if opts.ltitle!="":
        sf=searchFolder(opts.ltitle, recordedpath)
        print os.path.join(sf, destNameMKV(opts.ltitle,recpath,sf)+".mp4")
    elif opts.auto:
        sa=search_mp4(recpath, recordedpath)
        for t in sa:
            print "自動推測実行中"
            sf=searchFolder(t,recordedpath)
            if sf!="":
                print "移動先"
                print t+" : "+os.path.join(sf, destNameMP4(t, recpath,sf)+".mp4")
                print "実行中"
                execMove(t, recpath, recordedpath)
            else:
                print t+" can't find matching folder."
    elif opts.list:
        sa=search_mp4(recpath, recordedpath)
        for t in sa:
            sf=searchFolder(t,recordedpath)
            if sf!="":
                print t+" : "+os.path.join(sf, destNameMP4(t, recpath,sf)+".mp4")
    elif opts.etitle!="":
        execMove(opts.etitle,recpath, recordedpath)

