import os
import sys
from os import path
from calculate.lib.datavars import Variable,VariableError,ReadonlyVariable
from calculate.lib.utils.files import readLinesFile

from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_desktop3',sys.modules[__name__])

class VariableUrJidHost(ReadonlyVariable):
    """
    Jabber host for user
    """
    def get(self):
        userJid = self.Get("ur_jid")
        if userJid:
            return userJid.partition('@')[2]
        return ""

class VariableUrDomainSet(ReadonlyVariable):
    """
    Flag for determining domain user or local
    """
    def getUserDataInFile(self, login, filePasswd):
        return filter(lambda x: x[0]==login,
               map(lambda x: x.strip().split(':'),
               readLinesFile(filePasswd)))

    def get(self):
        ret = "off"
        userName = self.Get("ur_login")
        if userName:
            try:
                passwdUserData = self.getUserDataInFile(userName, "/etc/passwd")
            except:
                return ret
            if passwdUserData:
                passwdUserData = passwdUserData[0]
                try:
                    cacheUserData = self.getUserDataInFile(userName,
                        "/var/lib/calculate/calculate-client/cache/passwd")
                except:
                    return ret
                if cacheUserData:
                    cacheUserData = cacheUserData[0]
                    if cacheUserData == passwdUserData:
                        ret = "on"
            else:
                ret = "on"
        return ret

class VariableClDesktopXsession(ReadonlyVariable):
    """
    User current X session
    """
    def get(self):
        envXsessionFile = "/etc/env.d/90xsession"
        xsession = os.environ.get("XSESSION",None)
        desktopSession = os.environ.get("DESKTOP_SESSION",None)
        if not xsession:
            if os.path.exists(envXsessionFile):
                xsession = \
                    map(lambda x:x.partition("=")[2].strip("'\""),
                    filter(lambda x:x.startswith("XSESSION="),
                    filter(lambda x:not x.startswith("#"),
                    open(envXsessionFile,"r"))))
                if xsession:
                    xsession = xsession[-1]
        if xsession:
            if desktopSession and \
                any(x in desktopSession.lower()
                    for x in ("kde","xfce","gnome")):
                xsession = desktopSession
            if "kde" in xsession.lower():
                return "kde"
            elif "gnome" in xsession.lower():
                return "gnome"
            elif "xfce" in xsession.lower():
                return "xfce"
            else:
                return xsession.lower()
        return ""

class VariableClDesktopGstData(ReadonlyVariable):
    """
    GStreamer data
    """
    def get(self):
        # try import gst
        try:
            olderr = os.dup(sys.stderr.fileno())
            os.close(sys.stderr.fileno())
            import gst
            import gst.interfaces
        except ImportError:
            gst = None
        finally:
            os.dup2(olderr,sys.stderr.fileno())
        if gst is None:
            return {}

        outdata = {}
        try:
            pipeline = "alsamixer"
            alsamixer = gst.element_factory_make(pipeline)
            res = alsamixer.set_state(gst.STATE_PAUSED)
            if res == gst.STATE_CHANGE_SUCCESS:
                outdata['device_name'] = alsamixer.get_property("device-name")
                outdata['long_name'] = alsamixer.get_factory().get_longname()
                outdata['internal_name'] = filter(str.isalnum,
                                "%s (%s)"%(outdata['device_name'],
                                           outdata['long_name']))
                outdata['channels'] = []
                for t in alsamixer.list_tracks():
                    if t.flags & gst.interfaces.MIXER_TRACK_OUTPUT:
                        if t.flags & gst.interfaces.MIXER_TRACK_MASTER or \
                            any(x in t.label 
                                for x in ("Wave","Front","LFE","Center",
                                          "Head","Side","Speaker",
                                          "Surround","PCM")):
                            outdata['channels'].append(t.label)
                            if t.flags & gst.interfaces.MIXER_TRACK_MASTER:
                                outdata['master_channel'] = t.label
        except:
            pass
        return outdata

class VariableClDesktopGstCard(ReadonlyVariable):
    """
    Internal card name for xfce mixer
    """
    def get(self):
        return self.Get('cl_desktop_gst_data').get('internal_name','')

class VariableClDesktopGstMasterchannel(ReadonlyVariable):
    """
    Master track name
    """
    def get(self):
        return self.Get('cl_desktop_gst_data').get('master_channel','')


class VariableClDesktopXfceMixer(ReadonlyVariable):
    """
    List of channel for xfce-perchannel mixer
    """
    def get(self):
        return "\n".join(
               map(lambda x:'      <value type="string" value="%s" />'%x,
               self.Get('cl_desktop_gst_data').get('channels',[])))
