import os
import threading

import player_presentation_command
import player_presentation_errors
import player_presentation_openoffice
import player_presentation_properties
import player_presentation_utils


class QueueRunner(threading.Thread):

    def __init__(self, queue, identity, log, oo_executable, execute_oo):
        threading.Thread.__init__(self)
        self.log = log
        self.queue = queue
        self.stopped = False
        self.running_media = None
        self.oo_executable = oo_executable
        self.oo = None
        self.execute_oo = execute_oo
        self.properties = player_presentation_properties.Properties()
        self.caps = {
            'version': ['1'],
            'identity': [identity],
            'media_class': ['presentation'],
            'process_id': ['%d' % (os.getpid(),)],
            'command': ['wait']
        }
        self.version = '1'

    @player_presentation_utils.log_method
    def start_oo(self):
        if self.oo is None:
            self.oo = player_presentation_openoffice.OpenOffice(
                            executable=self.oo_executable,
                            properties=self.properties,
                            log=self.log,
                            start=self.execute_oo)

    @player_presentation_utils.log_method
    def run(self):
        while not self.stopped:
            command = self.queue.get()
            if isinstance(command, player_presentation_command.Command):
                command.set_runner(self)
                command.run()
            elif command is None:
                return

    @player_presentation_utils.log_method
    def stop(self):
        self.stopped = True
        if self.running_media is not None:
            self.running_media.stop()
        if self.oo is not None:
            self.oo.terminate()
            self.oo = None
        self.queue.put(None)

    @player_presentation_utils.log_method
    def media_is_running(self):
        if self.running_media is None:
            return False
        if self.running_media.presentation is None:
            return False
        try:
            return self.running_media.presentation.isRunning()
        except player_presentation_errors.DisposedException:
            return False

