import os
import subprocess
import fcntl

import lib.utils as utils
import lib.server as server

from select import select

def _setup_mythfilename(self):
    # mythtv:mythtv@192.168.3.110:6543/1002_20070426230000.nuv
    try:
        _mysql = self.args["input"].split("@")[0].split(":")
    except IndexError, e:
        _mysql = ["mythtv", "mythtv"]

    try:
        _args = self.args["input"].split("@")[1].split(":")
    except IndexError, e:
        _args = self.args["input"].split(":")

    gmyth_dict = {}
    gmyth_dict["mysql"] = _mysql
    gmyth_dict["backend"] = _args[0]
    gmyth_dict["port"] = _args[1].split("/", 1)[0]

    _tmp_file = _args[1].split("/", 1)[1]

    if _tmp_file.find("channel") >= 0:
        gmyth_dict["kind"] = "c"
        gmyth_dict["cfile"] = _tmp_file.split("=")[1]
    else:
        gmyth_dict["kind"] = "f"
        gmyth_dict["cfile"] = _tmp_file

    self.args["input"] = "-"
    return gmyth_dict
# _setup_mythfilename

def _setup_mythfile(err):
    size = err.readline().split("Size:")[1]
    flags = fcntl.fcntl (err, fcntl.F_GETFL, 0) | os.O_NONBLOCK
    fcntl.fcntl(err, fcntl.F_SETFL, flags)
    return size
# _setup_mythfile

def _setup_gmythcat(self):
    gmyth_cat = utils.which("gmyth-cat")
    if self.args.has_key("gmyth-cat"):
        return [ utils.which("gmyth-cat"),
                 "-h", self.args["gmyth-cat"]["backend"],
                 "-p", self.args["gmyth-cat"]["port"],
                 "-" + self.args["gmyth-cat"]["kind"],
                 self.args["gmyth-cat"]["cfile"]
                 ]
    else:
        self.log.error(self.tid, "Error: URI error")
        return []
# _setup_gmythcat

def start_myth(self, outfd):
    opts = _setup_gmythcat(self)
    try:
        self.gmyth = subprocess.Popen(opts, stdout=subprocess.PIPE,
                                      stderr=subprocess.PIPE,
                                      close_fds=True)
    except Exception, e:
        self.log.error(self.tid, "Error: gmyth-cat: %s" % e)
        return False

    if not self._run_mencoder(input=self.gmyth.stdout,
                              output=subprocess.PIPE):
        return False

    if self.args["gmyth-cat"]["kind"] == "f":
        try:
            size = _setup_mythfile(self.gmyth.stderr)
            self.log.debug(self.tid, "Info: Size of file: %s" % size)
        except Exception, e:
            self.log.error(self.tid, "Error: Problems getting size of"\
                           " file: %s" % e)
            outfd.write("Error: Problems getting size of file: %s" % e)
            return False

    outfd.write("OK     ")

    try:
        while self.proc and self.proc.poll() == None:
            r, w, x = select([self.gmyth.stderr, self.proc.stdout],
                             [], [], 0)
            if self.proc.stdout in r:
                d = self.proc.stdout.read(4096)
                outfd.write(d)

            if self.gmyth.stderr in r:
                partial = self.gmyth.stderr.readline()
                if partial != "":
                    self.status = utils.progress_bar(int(partial),
                                                     int(size), 50)

    except IndexError, e:
        pass
    except Exception, e:
        self.log.error(self.tid, "Error: %s" % e)
        return False

    self.log.info(self.tid, "OK: Done")
    return True
# _start_myth()
