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

import os
import os.path
import optparse
import sys

import configreader
import recdblist
import auto_move
import guess
import rec10d
recordedpath=unicode(configreader.getConfPath("recorded"),'utf-8')
recpath=unicode(configreader.getConfPath("recpath"),'utf-8')

if __name__ == "__main__":
    usage="usage: %prog read -h"
    version="%prog 0.9.10"
    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("-D","--Delete",action="store_true",dest="delete",default=False,help="auto delete tempfile 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)")
    parser.add_option("-t","--tssearch",action="store_true",dest="tssearch",default=False,help="Ts move auto search")
    parser.add_option("-T","--Tsmove",action="store_true",dest="tsmove",default=False,help="Ts auto move.")
    parser.add_option("-S","--SeriesNum",action="store",type="string",dest="seriespath",default="",metavar="TITLE",help="Search Series Number in the path.")
    parser.add_option("-m","--manual",action="store_true",dest="manual",default=False,help="manual classifying mode asking for y/n(not a test)")
    parser.add_option("-r","--rec10",action="store_true",dest="rec10",default=False,help="save moving plan in SQL table")
    #parser.add_option("-f","--filenumlist",action="store_true",dest="filenumlist",default=False,help="Guess Program Number.")

    (opts,args)=parser.parse_args(sys.argv)
    if opts.ltitle!="":##-sの場合
        ltitle=unicode(opts.ltitle,'utf-8')
        sf=guess.searchFolder(ltitle, recordedpath)
        print "###MKV###"
        recdblist.printutf8(os.path.join(sf, auto_move.getMoveDestpath(ltitle,recpath,sf,".mkv")+".mkv"),verbose_level=100)
        print "\n"
        print "###MP4###"
        recdblist.printutf8(os.path.join(sf, auto_move.getMoveDestpath(ltitle,recpath,sf,".mp4")+".mp4"),verbose_level=100)
        print "\n"
    elif opts.auto:##-A の場合
        sa=auto_move.searchFile(recpath, recordedpath, ".mkv")
        for t in sa:
            recdblist.printutf8(u"自動推測実行中-MKV",verbose_level=100)
            sf=guess.searchFolder(t,recordedpath)
            if sf!="":
                recdblist.printutf8(u"移動先",verbose_level=100)
                recdblist.printutf8(t+" : "+os.path.join(sf, auto_move.getMoveDestpath(t, recpath,sf,".mkv")+".mkv"),verbose_level=100)
                recdblist.printutf8(u"実行中",verbose_level=100)
                auto_move.execMove(t, recpath, recordedpath,".mkv",1)
            else:
                recdblist.printutf8(t+" can't find matching folder",verbose_level=100)
        sa=auto_move.searchFile(recpath, recordedpath, ".mp4")
        for t in sa:
            recdblist.printutf8(u"自動推測実行中-MP4",verbose_level=100)
            sf=guess.searchFolder(t,recordedpath,200)
            if sf!="":
                recdblist.printutf8(u"移動先",verbose_level=100)
                recdblist.printutf8(t+" : "+os.path.join(sf, auto_move.getMoveDestpath(t, recpath,sf,".mp4")+".mp4"),verbose_level=100)
                recdblist.printutf8(u"実行中",verbose_level=100)
                auto_move.execMove(t, recpath, recordedpath,".mp4",1)
            else:
                recdblist.printutf8(t+" can't find matching folder",verbose_level=100)
    elif opts.manual:##-m の場合
        # mkv無視します
        sa=auto_move.searchFile(recpath, recordedpath, ".mp4")
        for t in sa:
            sf=guess.searchFolder(t,recordedpath,200)
            if sf!="":
                recdblist.printutf8(u"○候補："+os.path.join(sf, auto_move.getMoveDestpath(t, recpath,sf,".mp4")+".mp4"),verbose_level=100)
                ans = raw_input("移動しますか? (y/n/h)")
                if ans == 'y':
                    recdblist.printutf8(u"移動を実行します",verbose_level=100)
                    auto_move.execMove(t, recpath, recordedpath,".mp4",1)
                elif ans == 'n':
                    recdblist.printutf8(u"移動を中止します",verbose_level=100)
                elif ans == 'h':
                    recdblist.printutf8(u"移動のヒント",verbose_level=100)
                    recdblist.printutf8(u"FIXME:not implemented",verbose_level=100)
            else:
                recdblist.printutf8(u"×不明："+t,verbose_level=100)
    elif opts.rec10:##-r の場合
        # mkv無視します
        dbl=rec10d.rec10db.select_move_auto_classify()
        if len(dbl)>0:
            for dbt in dbl:
                t= dbt[1]
                auto_move.execMove(t, recpath, recordedpath,".mp4",1)
        rec10d.rec10db.delete_refresh_auto_classify()
        sa=auto_move.searchFile(recpath, recordedpath, ".mp4")
        for t in sa:
            sf=guess.searchFolder(t,recordedpath,200)
            if sf!="":
                frompath = os.path.join(recpath, t + ".mp4")
                topath = os.path.join(sf, auto_move.getMoveDestpath(t, recpath,sf,".mp4")+".mp4")
                rec10d.rec10db.add_auto_classify(t,frompath, topath) 
    elif opts.delete:##-Dの場合
        sa=auto_move.searchFile(recpath, recordedpath,".mkv")
        for t in sa:
            auto_move.execDelete(t, recpath)
        sa=auto_move.searchFile(recpath, recordedpath,".mp4")
        for t in sa:
            auto_move.execDelete(t, recpath)
    elif opts.list:##-lの場合
        sa=auto_move.searchFile(recpath, recordedpath,".mkv")
        for t in sa:
            sf=guess.searchFolder(t,recordedpath)
            if sf!="":
                recdblist.printutf8(t+u" : "+os.path.join(sf, auto_move.getMoveDestpath(t, recpath,sf,".mkv")+".mkv"),verbose_level=100)
        sa=auto_move.searchFile(recpath, recordedpath,".mp4")
        for t in sa:
            sf=guess.searchFolder(t,recordedpath)
            if sf!="":
                recdblist.printutf8(t+u" : "+os.path.join(sf, auto_move.getMoveDestpath(t, recpath,sf,".mp4")+".mp4"),verbose_level=100)
    elif opts.etitle!="":
        if os.path.exists(os.path.join(recpath, etitle+".mkv")):
            auto_move.execMove(etitle,recpath, recordedpath,".mkv",1)
        elif os.path.exists(os.path.join(recpath, etitle+".mp4")):
            auto_move.execMove(etitle,recpath, recordedpath,".mp4",1)
    elif opts.tssearch:## -tの場合
        tsmovepath=""
        try:
            tsmovepath=unicode(configreader.getConfPath("ts_movepath"),'utf-8')
        except:
            ""
        if tsmovepath!="":
            sa=auto_move.searchFile(recpath, tsmovepath,".ts")
            for t in sa:
                sf=guess.searchFolder(t,tsmovepath,700)
                if sf!="":
                    recdblist.printutf8(t+u" : "+os.path.join(sf, auto_move.getMoveDestpath(t, recpath,sf,".ts")+".ts"))
                    print "\n"
            sa=auto_move.searchFile(recpath, tsmovepath,".ts")
        else:
            recdblist.printutf8(u"ts_movepathが設定されていません。/etc/rec10.confを設定してください。",verbose_level=100)
    elif opts.tsmove:##-Tの場合
        tsmovepath=""
        try:
            tsmovepath=unicode(configreader.getConfPath("ts_movepath"),'utf-8')
        except:
            ""
        if tsmovepath!="":
            sa=auto_move.searchFile(recpath, tsmovepath,".ts")
            for t in sa:
                sf=guess.searchFolder(t,tsmovepath,700)
                if sf!="":
                    recdblist.printutf8(u"移動先",verbose_level=100)
                    recdblist.printutf8(t+" : "+os.path.join(sf, auto_move.getMoveDestpath(t, recpath,sf,".ts")+".ts"),verbose_level=100)
                    recdblist.printutf8(u"実行中",verbose_level=100)
                    auto_move.execMove(t, recpath, tsmovepath,".ts",0)
            sa=auto_move.searchFile(recpath, tsmovepath,".ts")
        else:
            recdblist.printutf8(u"ts_movepathが設定されていません。/etc/rec10.confを設定してください。",verbose_level=100)
    elif opts.seriespath!="":##-Sの場合##与えられたパスにシリーズがそろっているかを調べる。
        ss=guess.detSeriesNum(opts.seriespath)
        for sstitle, ssv in ss.iteritems():
            if len(ssv)>0:
                maxt=0
                bt=0
                alr=[]
                for ssi,ssiv in ssv.iteritems():
                    alr.append(ssi)
                    if maxt<ssi:
                        maxt=ssi
                alr=list(set(alr))
                alr.sort()
                alr.reverse()
                nuke=""
                for i in xrange(1,maxt+1,1):
                    if alr.count(i)==0:
                        nuke=nuke+str(i)+","
                if len(nuke)==0:
                    recdblist.printutf8(sstitle+" "+str(maxt))
                else:
                    recdblist.printutf8(u"**"+sstitle+" |"+str(maxt)+"| "+nuke)
