#!/usr/bin/python
#coding:utf-8

'''     配置文件解析   '''
'''
##############################################################################
#--- 配 置 文 件 格 式 ----
[section1]
option1 = Value
option2 = Value
    ... ...
optionN = Value

[section2]
option2 = Value
  ... ...
# --------------
##############################################################################
'''
import os
import ConfigParser             #
from threading import Lock      # 导入线程锁
import re                       # 正则表达式
from os import getenv

#
# ## ConfigParser option  大小写问题
#
# class MyConfigParser(ConfigParser.ConfigParser):
#     # def __init__(self):
#     #     super(MyConfigParser, self).__init__()
#     def optionxform(self, optionstr):
#         return optionstr



################################
#  ConfigFileParser
################################
class ConfigFileParser(object):

    __configMutex = Lock() # 线程锁

    def __init__(self):

        self.__configPath = getenv('MCOS_CONFIG_FILE')              # 获取 配置文件路径
        if self.__configPath == None or self.__configPath == "":
            self.__configPath = "./default.conf"

        fileName = re.sub("^.*/","",self.__configPath)              # 获取文件名
        self.__configDir = re.sub(fileName,"",self.__configPath)    # 获取文件目录
        if self.__configDir == "":
            self.__configDir = "./"

        # print fileName
        # print self.__configDir
        if False == os.path.isdir(self.__configDir):    # 如果文件目录不存在，则新建目录
            os.makedirs(self.__configDir)

        if False == os.path.isfile(self.__configPath):  # 如果文件不存在则新建文件
            file=open(self.__configPath,'w')
            file.close()

        cmd = "chmod o+w  %s" % self.__configPath  # 给文件添加写权限
        os.system(cmd)
        self.conf = ConfigParser.ConfigParser()         # 实例化 ConfigParser 对象
        # self.conf = MyConfigParser()         # 实例化 ConfigParser 对象

    # def __del__(self):
    #     #del self.conf
    #     print "----ConfigFileParser -- del"


    ###############################################
    #
    #   getValue
    #   不存在返回空 ""
    ###############################################
    def getValue(self, section, option):
        """获取指定的section， 指定的option的值"""
        value = ""
        self.__configMutex.acquire()           #   线程锁

        self.conf.read(self.__configPath)      #   读取文件

        if self.conf.has_section(section):
            if self.conf.has_option(section, option):
                value = self.conf.get(section, option)
        self.__configMutex.release()           #   释放线程锁
        return value

    ##########################################################
    #   名称 ： addSection
    #   功能 ： 添加 section
    #   描述 ： self.__configPath，文件不存在会新建文件
    #          option, value 要么全部为None，要么全部不为 None.
    #   参数 ：
    #        new_section
    #        option      = None
    #        value       = None
    #   返回 ：
    #       成功    True
    #       失败    False
    ##########################################################
    def addSection(self, new_section, option=None, value=None):
        """写入指定section, 增加新option的值"""
        ret = False
        self.__configMutex.acquire()
        self.conf.read(self.__configPath)
        if not self.conf.has_section(new_section):             # 如果 new_section 不存在
            self.conf.add_section(new_section)
            #判断键值和数据是否有效
            if option and value:
                self.conf.set(new_section, option, value)
            self.conf.write(open(self.__configPath,"w"))               #文件 不存在则新建

            ret = True
        self.__configMutex.release()
        return ret
    #############################################
    #   addOption
    #   描述 ： 前提 section 必须存在，否则返回 False
    #           option 必须不存在，否则返回 False
    #   返回 ：
    #      成功     True
    #      失败     False
    #############################################
    def addOption(self, section, option, value):
        """在指定的section, 增加新option的值"""
        ret = False
        self.__configMutex.acquire()
        self.conf.read(self.__configPath)
        if self.conf.has_section(section):                  # 判断 section是否存在
            if not self.conf.has_option(section, option):   # 判断 option 是否存在
                self.conf.set(section, option, value)
                self.conf.write(open(self.__configPath,"w"))
                ret = True
        self.__configMutex.release()
        return ret

    #================================ 查 询  =================================#
    #################################
    #   has_section
    #   不存在返回  False
    #   存在返回   True
    #################################
    def has_section(self, section):
        """是否存在指定的section"""
        ret = False
        self.__configMutex.acquire()
        self.conf.read(self.__configPath)
        if self.conf.has_section(section):
            ret = True
        self.__configMutex.release()
        return ret
    #################################
    #   has_option
    #   不存在返回  False
    #   存在返回   True
    #################################
    def has_option(self, section, option):
        """是否存在指定的option"""
        ret = False
        self.__configMutex.acquire()
        self.conf.read(self.__configPath)
        if self.conf.has_section(section):
            if self.conf.has_option(section, option):
                ret = True
        self.__configMutex.release()
        return ret

    #################################
    #   名称 ： options
    #   描述 ： 获取 section 下的所有 option,没有option则返回 空列表 []
    #   返回 ：
    #       成功  列表["oprions1","oprions2", .... "oprionsN"]
    #################################
    def options(self, section):
        """返回所有的option"""
        self.__configMutex.acquire()
        self.conf.read(self.__configPath)
        ret =self.conf.options(section);
        self.__configMutex.release()
        return ret
    #################################
    #   sections
    #   返回列表  []
    #################################
    def sections(self):
        """返回所有的section"""
        self.__configMutex.acquire()
        self.conf.read(self.__configPath)
        ret = self.conf.sections()
        self.__configMutex.release()
        return ret


    def changeSectionValue(self, section, option, value):
        """更新指定section, option的值"""
        ret = False
        self.__configMutex.acquire()
        self.conf.read(self.__configPath)

        if self.conf.has_section(section):
            if self.conf.has_option(section, option):
                self.conf.set(section, option, value)
                self.conf.write(open(self.__configPath,"w"))
                ret = True
        self.__configMutex.release()
        return ret

    #================================ 删 除  ===================================#
    #################################
    #
    #################################
    def remove_section(self, section):
        """删除指定的section"""
        ret = False
        self.__configMutex.acquire()
        self.conf.read(self.__configPath)
        if self.conf.has_section(section):
            self.conf.remove_section(section)
            self.conf.write(open(self.__configPath,"w"))
            ret = True
        self.__configMutex.release()
        return ret
    #################################
    #
    #################################
    def remove_option(self, section, option):
        """删除指定的option"""
        ret = False
        self.__configMutex.acquire()
        self.conf.read(self.__configPath)
        if self.conf.has_section(section):
            if self.conf.has_option(section, option):
                self.conf.remove_option(section, option)
                self.conf.write(open(self.__configPath,"w"))
                ret = True
        self.__configMutex.release()
        return ret
    #################################
    # 描述：删除 section下 的所有 option
    #################################
    def remove_all_options(self,section):
        optionList = self.options(section)
        # print "检查 optons ",section, optionList
        for i in range(len(optionList)):
            print "del:", section,optionList[i]
            print  self.remove_option(section,optionList[i])

        # print "删除----后:  ",self.options(section)
    #================================ update  ===================================#
    #################################
    #   添加 或者 更新 value
    #################################
    def addOrUpdateValue(self, section, option, value):
        section = str(section)
        option = str(option)
        value = str(value)
        if self.has_section(section):
            if self.has_option(section, option):
                self.changeSectionValue(section, option, value)
            else:
                self.addOption(section, option, value)
        else:
            self.addSection(section, option, value)

################################################
#  单元测试
################################################
def conf_test():

    from os import environ

    _dirs = os.path.abspath(__file__)  # 当前文件路径
    _dirs = os.path.dirname(_dirs)     # 当前文件目录
    path = _dirs + "/" + "default.conf"
    environ["MCOS_CONFIG_FILE"] = path

    conf = ConfigFileParser()

    print "-------------------  添加  ---------------------------"
    print conf.addSection("centerInfo")                         # 添加 section
    print conf.addSection("defaultCenterInfo")                  # 添加 section
    print conf.addSection("LoginInfo","userName1","1234455")    # 添加 section

    print conf.addOption("LoginInfo","userName2","Pass1234")
    print conf.addOption("LoginInfo","userName3","Pass1234") #
    print conf.addOption("LoginInfo","userName3","Pass1234") #
    print conf.addOption("LoginInfo","LoginInfo","Pass1234") #
    print conf.addOption("defaultCenterInfo","请选择平台","centerName")
    print conf.addOption("centerInfo","192.168.102.33","centerName")
    conf.changeSectionValue("LoginInfo","userName3",[])
    print conf.getValue("LoginInfo","userName3")


    # print conf.addOption("LoginInfo","192.168.102.33","192.168.102.33")
    # print conf.addOption("LoginInfo","192.168.102.34","192.168.102.33")

    #print conf.addSection("LoginInfo","passwd","Pass1234")

    # print conf.addSection("updates","updates","auto_upgrade")
    # print conf.addSection("autoScreenState","autoScreenState","yes")
    # print conf.addSection("terminaltype","type","desktopVM")

    # print "- -- -- -- -- -- -- -- -- -- -- -- -"
    # print conf.addSection("usbset")
    #print conf.addOption("LoginInfo","passwd","Pass1234")
    #
    # print "------------------  change  --------------------------"
    # print conf.addSection("names","name1","job")
    # print conf.changeSectionValue("names","name1","Jek")


    print "------------------  删除 -------------------------"
    # print conf.remove_option("defaultCenterInfo","请选择平台")
    # print conf.remove_option("LoginInfo","username1")
    # print conf.remove_option("LoginInfo","username2")
    # print conf.remove_option("LoginInfo","username3")
    # conf.remove_all_options("LoginInfo")
    # print conf.remove_option("defaultCenterInfo","username1")
    # print conf.remove_section("names")


    # print "-------------------      ---------------------------"
    # print conf.getValue("LoginInfo","userName")
    # print conf.getValue("LoginInfo","passwd")
    # print conf.getValue("LoginInfo","centerIP")
    # print conf.addSection("localnetworklist")
    # # if False == conf.has_section("localnetworklist"):
    # #     print conf.addSection("localnetworklist")

    #print conf.changeSectionValue("LoginInfo","userName","jxm")
    # print "------------------- list ---------------------------"
    # list_sections = conf.sections()
    # print list_sections
    #
    # list_options = conf.options(list_sections[0])
    # print list_options
    #
    # value = conf.getValue(list_sections[0],list_options[0])
    # print value

    # print conf.sections()
    print conf.options('LoginInfo')


def conf_test2():

    from os import environ
    _dirs = os.path.abspath(__file__)  # 当前文件路径
    _dirs = os.path.dirname(_dirs)     # 当前文件目录
    path = _dirs + "/" + "default.conf"
    environ["MCOS_CONFIG_FILE"] = path

    conf = ConfigFileParser()

    print "-------------------  添加  ---------------------------"
    print conf.addSection("centerInfo")                         # 添加 section
    print conf.addSection("defaultCenterInfo")                  # 添加 section
    print conf.addSection("LoginInfo","userName1","1234455")    # 添加 section

    print conf.addOption("LoginInfo","userName2","Pass1234")
    print conf.addOption("LoginInfo","userName3","Pass1234") #
    print conf.addOption("LoginInfo","userName3","Pass1234") #
    print conf.addOption("LoginInfo","LoginInfo",[]) #
    print conf.addOption("defaultCenterInfo","请选择平台","centerName")
    print conf.addOption("centerInfo","192.168.102.33","centerName")
    # conf.changeSectionValue("LoginInfo","userName3",[])
    # print conf.getValue("LoginInfo","userName3")


if __name__ == "__main__":
    conf_test2()
