import platform
if platform.system() == 'TCC LE ':
    platform.system = lambda: 'Windows'

import os
import sys
from optparse import OptionParser

from twisted.internet import gtk2reactor, defer
gtk2reactor.install()
from twisted.internet import reactor, task

from elisa.plugins.gstreamer.gst_metadata import GstMetadata, \
        GstMetadataPipeline, supported_keys
from elisa.plugins.gstreamer.amp_master import GstMetadataAmpClient
from elisa.plugins.gstreamer import gst_metadata, pipeline
from elisa.core.media_uri import MediaUri
from elisa.core import log
from elisa.extern.log.log import getFailureMessage
from elisa.core.config import Config
from elisa.extern.configobj import Section
from elisa.core import common

# useful when debugging the protocol
import sys
from twisted.python import log as tlog
tlog.startLogging(sys.stdout, setStdout=0)

pipeline.THUMBNAIL_DIR = 'thumbs'
import shutil
#try:
#    shutil.rmtree('thumbs')
#except: pass
GstMetadataPipeline.thumb_timeout = 5
GstMetadataPipeline.use_decodebin2 = True

class App(object):
    def __init__(self):
        self.running = False

    def created_cb(self, component, keys, files):
        self.component = component

        def get_metadata_cb(result):
            print 'get metadata callback %s' % result

            return result

        def get_metadata_eb(failure):
            print 'get metadata failure %s' % \
                getFailureMessage(failure)

            return None

        lst = []
        while files:
            try:
                filename = files.pop()
                filename = os.path.abspath(filename)
            except IndexError:
                break
            
            if os.path.isdir(filename):
                files.extend([os.path.join(filename, i)
                        for i in os.listdir(filename)])
                continue

            try:
                uri = MediaUri('file://' + filename)
            except: continue
            uri.path = filename
            metadata = {'uri': uri}
            metadata.update(dict((key, None) for key in keys))

            dfr = component.get_metadata(metadata)
            dfr.addCallback(get_metadata_cb)
            dfr.addErrback(get_metadata_eb)
            lst.append(dfr)

        def iterate_files_done(result):
            return component.clean().addCallback(lambda result: reactor.stop())

        dfr = defer.DeferredList(lst)
        dfr.addCallback(iterate_files_done)

        return dfr

    def created_eb(self, failure):
        print 'failure creating component %s' % \
                getFailureMessage(failure)
        reactor.stop()

    def start(self, keys, files):
        log.init()
        self.config = Config('thumb.conf')
        common.application = self
        dfr = GstMetadataAmpClient.create()
        dfr.addCallback(self.created_cb, keys, files)
        dfr.addErrback(self.created_eb)
        self.running=True

    def run(self):
        parser = OptionParser(usage='%prog [options] files')
        keys = list(supported_keys - set(['uri']))
        parser.add_option('-k', '--key',
                type='choice', choices=keys,
                action='append', dest='keys')
        opts, args = parser.parse_args()
        if not args:
            parser.error('no files specified')
            return

        reactor.callLater(0, self.start, opts.keys or keys, args)
        reactor.run()

if __name__ == '__main__':
    App().run()
