# transcode.py - transcode command
#
# Copyright 2007 Nokia
# Author: Daniel d'Andrada T. de Carvalho <daniel.carvalho@indt.org.br>
#
# This file is part of mediahandler-skeleton.
#
# mediahandler-skeleton is free software: you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# mediahandler-skeleton is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with mediahandler-proxy. If not, see <http://www.gnu.org/licenses/>.

from command import Command

import subprocess
import re
from time import sleep
import shared

class Transcode(Command):
    def __init__(self, sock):
        Command.__init__(self, 'transcode')

        self.sock = sock

        self.input_path = ''
        self.output_path = ''
        self.width = 0 # In pixels
        self.height = 0 # In pixels
        self.video_encoder = ''
        self.video_data_rate = 0 # In bps
        self.audio_data_rate = 0 # In bps
        self.frame_rate = 0 # In frames per second

    def parse(self, command):

        params = command.split('|')

        if len(params) != 8:
            return False

        self.input_path = params[0]
        self.output_path = params[1]

        try:
            self.width = int(params[2])
            self.height = int(params[3])
            self.video_encoder = params[4]
            self.video_data_rate = int(params[5])
            self.audio_data_rate = int(params[6])
            self.frame_rate = int(params[7])
        except ValueError:
            return False

        return True

    def execute(self):

        keep_converting = True
        percentage = 0
        result = 'error'

        while keep_converting and percentage <= 100:
            self.sock.send('<progress>' + str(percentage) + '00</progress>')

            data = self.sock.recv(1024)
            reply = self._parse_progress_reply(data)

            if reply != 'proceed':
                keep_converting = False

            sleep(0.5)
            percentage += 1

        if keep_converting:
            # The user didn't abort the conversion

            # We don't want a console window to popup
            # This startupinfo stuff will to the trick
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

            subprocess.call(r'copy /Y "%s" "%s"' %\
                    (shared.video_filepath, self.output_path),
                    shell=True,
                    startupinfo=startupinfo)

            result = 'ok'
        else:
            # The user aborted the conversion
            result = 'aborted'

        return result

    def _parse_progress_reply(self, string):
        match = re.compile(r'(?<=\<progress-reply\>)(.+)(?=\</progress-reply\>)').search(string)

        if match == None:
            return 'abort'
        else:
            return match.group()
