# -*- coding: utf-8 -*-
import logging, mv_common
import re
import os


def mplayer_saver_check (cmd,templatefile):
    logging.debug("    Checking for heartbeat command in mplayer.conf")
    mplayerconf = "/etc/mplayer/mplayer.conf"
    if not os.path.exists(mplayerconf):
        logging.debug("    copying in mplayer template file")
        mv_common.cp_and_log(templatefile, mplayerconf)

    try:
        f = open(mplayerconf, 'r')
        mplayerconf_contents = f.readlines()
        f.close()
    except:
        logging.debug("    Couldn't open %s for reading",mplayerconf)
        mplayerconf_contents = "#\n"

    try:
        f = open(mplayerconf, 'w')
    except:
        logging.debug("    Couldn't open %s for writing",mplayerconf)
        return

    for line in mplayerconf_contents:
        if re.match("^.*stop-xscreensaver",line):
            continue
        elif re.match("^.*heartbeat-cmd",line):
            continue
        else:
            f.write(line)

    f.write("stop-xscreensaver = 0\n")
    line='''heartbeat-cmd="%s"\n''' %cmd
    f.write(line)
    f.close()


def killxscreensaver():
    logging.info("    Stopping xscreensaver")
    cmd="xscreensaver-command --exit "
    mv_common.runcmd(cmd)
    cmd="killall xscreensaver "
    mv_common.runcmd(cmd)

def killgscreensaver():
    logging.info("    Stopping gnome-screensaver")
    cmd="gnome-screensaver-command --exit "
    mv_common.runcmd(cmd)
    cmd="killall gnome-screensaver "
    mv_common.runcmd(cmd)


def setup_x_screensaver(idle,theme,screenconfigfile,templatefile):
    logging.info("    Configuring X screensaver")
    killgscreensaver()
    logging.debug("    Why can't xscreensaver have a nice configuration !")

    if not os.path.exists(screenconfigfile):
        logging.debug("   copying in new template file")
        mv_common.cp_and_log(templatefile,screenconfigfile)

    try:
        f = open(screenconfigfile, 'r')
        screenconfigcontents=f.readlines()
        f.close()
    except:
        logging.info("Couldn't open %s for reading",screenconfigfile)
        return
    try:
        f = open(screenconfigfile, 'w')
    except:
        logging.info("Couldn't open %s for writing",screenconfigfile)
        return

    startline=0
    foundline=0

    for k, line in enumerate(screenconfigcontents):
        if re.match("programs:",line):
            startline = k
        if re.search(theme,line):
            foundline = k
    themenumber=foundline-startline-1

    for line in screenconfigcontents:
        if re.match("selected.*$",line):
            continue

        if re.match("timeout",line):
            logging.info("    Setting idletime to %s",idle)
            outline = "timeout:   0:%s:00 \n" %idle
            f.write(outline)
        elif re.match("mode",line):
            if theme == "Random":
                logging.info("    Setting theme to %s", "Random")
                outline = "mode:    random \n"
                f.write(outline)
                outline = "selected:    -1 \n"
                f.write(outline)
                continue

            elif theme == "Blank":
                logging.info("    Setting theme to %s", "blank")
                outline = "mode:    blank \n"
                f.write(outline)
                outline = "selected:    -1 \n"
                f.write(outline)
                continue

            else:
                logging.info("    Setting theme to %s", theme)
                outline = "mode:    one\n"
                f.write(outline)
                logging.debug("    Theme number is %s",themenumber)
                outline = "selected:    %s\n" %themenumber
                f.write(outline)
                continue

        else:
            outline = line
            f.write(outline)
    f.close()
    logging.debug("__End of xscreensaver")

def setup_gnome_screensaver(theme,idletime):
    logging.info("    Configuring gnome screensaver")

    logging.info("    Disabling lock screen")
    cmd='''gconftool-2 --direct   --config-source xml:readwrite:/etc/gconf/gconf.xml.mandatory  --type bool   --set /apps/gnome-screensaver/lock_enabled false'''
    mv_common.runcmd(cmd)

    logging.info("    Setting idletime to %s",idletime)
    cmd='''gconftool-2 --direct  --config-source xml:readwrite:/etc/gconf/gconf.xml.mandatory  --type int -s "/apps/gnome-screensaver/idle_delay" %s''' %idletime
    mv_common.runcmd(cmd)

    logging.info("    Setting mode to single")
    cmd='''gconftool-2 --direct  --config-source xml:readwrite:/etc/gconf/gconf.xml.mandatory  --type string -s "/apps/gnome-screensaver/mode" single'''
    mv_common.runcmd(cmd)

    if theme == "Random":
        logging.info("    setting theme to random")
        cmd='''gconftool-2 --direct  --config-source xml:readwrite:/etc/gconf/gconf.xml.mandatory  --type string -s "/apps/gnome-screensaver/mode" random'''
        mv_common.runcmd(cmd)

    elif theme == "Blank":
        logging.info("    setting theme to blank")
        cmd='''gconftool-2 --direct  --config-source xml:readwrite:/etc/gconf/gconf.xml.mandatory  --type string -s "/apps/gnome-screensaver/themes" blank'''
        mv_common.runcmd(cmd)

    else:
        logging.info("    setting theme to %s",theme)
        cmd='''gconftool-2  --direct  --config-source xml:readwrite:/etc/gconf/gconf.xml.mandatory --set --type list --list-type=string /apps/gnome-screensaver/themes [screensavers-%s]''' %theme
        mv_common.runcmd(cmd)

    killxscreensaver()
    logging.info("__End gnome screensaver")


def start_screensaver(screensaver):
    logging.info("    Checking if screensaver needs to be started")
    if mv_common.check_service("frontend"):
        killxscreensaver()
        logging.info("    Frontend is running, starting screensaver")
        line='''su mythtv -c "DISPLAY=localhost:0 xscreensaver  -no-splash 2>&1 > /dev/null &" \n'''
        #line='''su mythtv -c "DISPLAY=localhost:0 xscreensaver  -no-splash \&" '''
        try:
            fout = open("/tmp/cmd.sh", "w")
            fout.write(line)
            fout.close()
            os.chmod("/tmp/cmd.sh",0755)
            cmd="/tmp/cmd.sh"
            os.system(cmd)
            os.remove("/tmp/cmd.sh")
        except:
            logging.info("    Couldn't start screensaver")




def setup_screensaver (systemconfig,data_config):
    if  mv_common.read_config(mv_common.module_config,"screensaver")  == False  :
        logging.info("____Skipping of Screensaver, config disabled____")
        return
    logging.info("____Start of screensaver configuration____")
    screensavertype = systemconfig.get("Screensavertype")
    theme = systemconfig.get("Screensavertheme")
    idletime = systemconfig.get("Screensaveridle")
    configfile = data_config.MYTHHOME+"/.xscreensaver"
    templatefile = systemconfig.get("TEMPLATES")+"/xscreensaver.template"
    mtemplate = systemconfig.get("TEMPLATES")+"/mplayer.conf.template"

    if screensavertype == "xscreensaver":
        mv_common.pacinstall("xscreensaver")
        mv_common.pacremove("gnome-screensaver")
        setup_x_screensaver(idletime, theme, configfile, templatefile)
        mplayer_saver_check("/usr/bin/xscreensaver-command -deactivate &",mtemplate)
        start_screensaver("xscreensaver")

    elif screensavertype == "gscreensaver":
        mv_common.pacinstall("xscreensaver")
        mv_common.pacinstall("gnome-screensaver")
        setup_gnome_screensaver(theme,idletime)
        mplayer_saver_check("/usr/bin/gnome-screensaver-command -p &",mtemplate)

    elif screensavertype == "none":
        mv_common.pacremove("xscreensaver")
        mv_common.pacremove("gnome-screensaver")
        killgscreensaver()
        killxscreensaver()

    elif screensavertype == "tinker" :
        logging.debug("    screensaver tinker mode detected")
    else:
        logging.debug("   Unknown screensaver")
    logging.info("__End of screensaver\n")



