"""
jxproperties.py


"""
import os
import sys
import simpleConfig
import re

CYGDRIVE = "/cygdrive/c"
JX_CLIENT = "/usr1/jx_client"
LINUX_CFG_DIR = JX_CLIENT + "/WHI.lni/JX/org/wh/config"
WINDOWS_CFG_DIR = "/WHI/JX/org/wh/config"
# accept any value as valid now since Standalone verion has all kinds of options
###VALID_OPTS = ('HOST', 'PORT', 'LOCATION')
ROOTLOGGER = 'log4j.rootLogger='
THRESHOLD = 'log4j.appender.R4.Threshold='
cre_rootlogger = re.compile(r'log4j.rootLogger=(\w+),R4')


__all__ = ['JXProperties', 'JXPropertiesError']


class JXPropertiesError(Exception):
    pass


class JXProperties:
    properties = {
        'ClientProperties' : ['', None],
        'POSProperties' : ['', 0],
        'POSRequestProperties' : ['', 0],
        'Log4j' : ['', None],
        'HTTPProxyProperties' : ['', None],
        'RemotingServerProperties' : ['', 0]
    }

    def __init__(self, ostype):
        ostype = ostype.lower()
        if ostype == 'linux':
            self.dir = LINUX_CFG_DIR
        elif ostype == 'windows':
            if sys.platform.startswith("win"):
                self.dir = WINDOWS_CFG_DIR
            elif sys.platform == "cygwin":
                self.dir = CYGDRIVE + WINDOWS_CFG_DIR
            elif sys.platform.startswith("linux"):
                self.dir = JX_CLIENT + WINDOWS_CFG_DIR
        else:
            raise JXPropertiesError("Invalid Operating System type: %s" % ostype)
        # each property within the file has up to two possible parameters. The third
        # parameter is a flag indicating if the property changed or not.  This flag
        # is used by the 'write()' method below
        self.properties = {
            'ClientProperties' : ['', None, False],
            'POSProperties' : ['', 0, False],
            'POSRequestProperties' : ['', 0, False],
            'Log4j' : [None, None, False],
            'HTTPProxyProperties' : ['', None, False],
            'RemotingServerProperties' : ['', 0, False]
        }
        self.changed = 0

    def read(self):
        for fname in self.properties.keys():
            path = os.path.join(self.dir, fname)
            path += '.properties'
            if fname == 'Log4j':
                fd = open(path)
                lines = fd.readlines()
                fd.close()
                for line in lines:
                    m = cre_rootlogger.match(line)
                    if m:
                        loglevel = m.group(1)
                        self.properties[fname][0] = loglevel
                        break
            else:
                try:
                    params = simpleConfig.options(path)
                except simpleConfig.Error, err:
                    err = "%s: %s" % (err, path)
                    raise JXPropertiesError(err)
                if fname == 'ClientProperties':
                    locID = params.get('LOCATION', '')
                    if isinstance(locID, list):
                        # if location id has blanks in it, it will be returned
                        # as a list so convert to a string
                        locID = ' '.join(locID)
                    self.properties[fname][0] = locID
                else:
                    host = params.get('HOST', '')
                    port = params.get('PORT', '')
                    self.properties[fname] = [host, port, False]
        return self.properties

    def write(self):
        for fname in self.properties.keys():
            # test flag to see if any parameter in this file changed
            if not self.properties[fname][2]:
                # skip, nothing changed
                continue
            path = os.path.join(self.dir, fname)
            path += '.properties'
            if fname == 'Log4j':
                fd = open(path, 'r+')
                lines = fd.readlines()
                for i in range(len(lines)):
                    if lines[i].startswith(ROOTLOGGER):
                        lines[i] = "%s%s,R4\r\n" % (ROOTLOGGER,
                                    self.properties[fname][0])
                    elif lines[i].startswith(THRESHOLD):
                        lines[i] = "%s%s\r\n" % (THRESHOLD,
                                    self.properties[fname][0])
                fd.seek(0)
                fd.truncate()
                fd.writelines(lines)
            else:
                fd = open(path, 'w')
                if fname == 'ClientProperties':
                    fd.write('LOCATION=%s\r\n' % self.properties[fname][0])
                else:
                    fd.write('HOST=%s\r\nPORT=%s\r\n' % (self.properties[fname][0],
                                                         self.properties[fname][1]))
            fd.close()
            # reset flag that indicates parameter change for this file
            self.properties[fname][2] = False
        # reset global changes counter
        self.changed = 0

    def update(self, fname, ix, value):
        if self.properties[fname][ix] == value:
            # nothing changed
            return
        oldvalue = self.properties[fname][ix]
        self.properties[fname][ix] = value
        # this code is necessary for loglevel comboBox when it first gets
        # initialized by glade.  Don't want to set changed flags
        if oldvalue is not None:
            # set the changed flag for this file
            self.properties[fname][2] = True
            # bump global number of parameters that have changed
            self.changed += 1

    def changes(self):
        return self.changed


if __name__ == "__main__":
    for ostype in ('linux', 'windows'):
        try:
            print "%s settings: %s" % (ostype.capitalize(), JXProperties(ostype).read())
        except JXPropertiesError, err:
            print err
