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

import re
from configFileParser import ConfigFileParser

import json

class UserInfoConfFile(ConfigFileParser):
    def __init__(self):
        super(UserInfoConfFile, self).__init__()
        try:
            print self.addSection("rememberUserInfo", "flag", "NO")  # 记住用户名/密码
            self.addSection("autologin", "flag", "NO")  # 自动登录

            self.addSection("userInfo", "userinfo", "")  # 添加 用户信息
            info = json.dumps([])
            self.addOption("userInfo", "userinfo", info)  #
            self.addSection("userInfoTmp", "userinfotmp", "")  # 临时用户信息
            self.addOption("userInfoTmp", "userinfotmp", info)  #

            self.addSection("defaultCenterInfo", )  # 平台信息   ip centerName
            self.addSection("centerInfo")  # 添加 添加平台
            self.addSection("defaultVM", "id", "NULL")  # 默认虚拟机 id
        except Exception as e:
            print "exception : ",e.message

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

    # ============================  中 心 操 作 ============================

    #############################################
    # 添加配置平台
    #############################################
    def addCenter(self, centerIp, centerName):
        "ip:port"
        centerIp = re.sub(':', '%', centerIp)
        self.addOption("centerInfo", centerIp, centerName)

    # 判断平台是否 已经存在
    def has_center(self, centerIp):
        centerIp = re.sub(':', '%', centerIp)
        if self.has_option("centerInfo", centerIp):
            return True
        else:
            return False

    #############################################
    # 删除配置平台
    #############################################
    def deleteCenter(self, centerIp):
        "ip:port"
        centerIp = re.sub(':', '%', centerIp)
        self.remove_option("centerInfo", centerIp)
        self.remove_option("defaultCenterInfo", centerIp)

    #############################################
    #   设置默认平台
    ###############################################
    def setDefaultCenter(self, centerIp):
        '''
            centterIp ： "ip:port"
            返回： True / False
        '''
        centerIp = re.sub(':', '%', centerIp)
        if self.has_option("centerInfo", centerIp):
            value = self.getValue("centerInfo", centerIp)
            # print " 存在"
            self.remove_all_options("defaultCenterInfo")
            self.addOption("defaultCenterInfo", centerIp, value)
            return True
        else:
            # print "不存在"
            self.remove_all_options("defaultCenterInfo")
            self.addOption("defaultCenterInfo", "请选择平台", "-----")
            return False

    ###############################################
    # 获取默认平台
    ###############################################
    def getDefaultCenter(self):
        "return ip:port"
        optionList = self.options("defaultCenterInfo")
        if len(optionList) == 0:
            self.setDefaultCenter("请选择平台")
            return "请选择平台"
        elif optionList[0] == "请选择平台":
            return "请选择平台"
        else:
            defaultCenter = optionList[0]
            # defaultCenter = defaultCenter + "("
            # defaultCenter = defaultCenter + self.getValue("defaultCenterInfo",optionList[0])
            # defaultCenter = defaultCenter + ")"

            defaultCenter = re.sub('%', ':', defaultCenter)
            return defaultCenter

    ###############################################
    # 获取 平台 列表
    ###############################################
    def getCenterList(self):
        '''
            return :[centerInfo1,centerInfo2...]

            centerInfo = {"centerIp":"","centerName":""}
        '''
        centerlist = []
        centerOptions = self.options("centerInfo")
        # print centerOptions
        for i in range(len(centerOptions)):
            centerInfo = {"centerIp": "", "centerName": ""}
            centerInfo["centerIp"] = centerIp = re.sub('%', ':', centerOptions[i])
            centerInfo["centerName"] = self.getValue("centerInfo", centerOptions[i])
            centerlist.append(centerInfo)
        return centerlist

    # ============================  用户名/密码 ============================
    # --------------------------
    # 保存登录用户名密码
    # --------------------------
    def setUserLoginInfo(self, userName, passwd):
        # print "set usrName : " , userName
        # self.remove_all_options("userInfo")
        # if userName != "":
        #     self.addOption("userInfo",userName,passwd)

        info = json.dumps([])
        self.changeSectionValue("userInfo", "userinfo", info)
        if userName != "":
            info = json.dumps([userName, passwd])
            self.changeSectionValue("userInfo", "userinfo", info)

    # --------------------------
    # 获取登录用户名密码
    # --------------------------
    def getUserLoginInfo(self):
        # optionList = self.options("userInfo")
        # if len(optionList) == 0:
        #     userName = ""
        #     passwd = ""
        # else:
        #     userName = optionList[0]
        #     passwd = self.getValue("userInfo", optionList[0])
        # return [userName, passwd]
        info = self.getValue("userInfo", "userinfo")
        if info == False:
            return  ["",""]

        list_info =  json.loads(info)
        if type(list_info) == list:
            if len(list_info) >= 2:
               return list_info
            else:
                return  ["",""]
        else:
            return  ["",""]

    # ============================  用户名/密码 ============================
    # --------------------------
    # 保存登录用户名密码
    # --------------------------
    def setUserLoginInfoTmp(self, userName, passwd):

        # self.remove_all_options("userInfoTmp")
        # if userName != "":
        #     self.addOption("userInfoTmp", userName, passwd)

        info = json.dumps([])
        self.changeSectionValue("userInfoTmp", "userinfotmp", info)
        if userName != "":
            info = json.dumps([userName, passwd])
            self.changeSectionValue("userInfoTmp", "userinfotmp",info)



    # --------------------------
    # 获取登录用户名密码
    # --------------------------
    def getUserLoginInfoTmp(self):
        # optionList = self.options("userInfoTmp")
        # if len(optionList) == 0:
        #     userName = ""
        #     passwd = ""
        # else:
        #     userName = optionList[0]
        #     passwd = self.getValue("userInfoTmp", optionList[0])
        # return [userName, passwd]

        info = self.getValue("userInfoTmp", "userinfotmp")
        if info == False:
            return  ["",""]
        list_info =  json.loads(info)
        if type(list_info) == list:
            if len(list_info) >= 2:
               return list_info
            else:
                return  ["",""]
        else:
            return  ["",""]


    # --------------------------
    # 设置记住用户名 密码
    # --------------------------
    def setRememberUserInfoFlag(self, flag=True):
        if flag:
            self.changeSectionValue("rememberUserInfo", "flag", "YES")
        else:
            self.changeSectionValue("rememberUserInfo", "flag", "NO")

    # --------------------------
    # 判断是否是记住密码
    # --------------------------
    def isRememberUserInfo(self):
        value = self.getValue("rememberUserInfo", "flag")
        # print value
        if value == "YES":
            return True
        else:
            return False

    # --------------------------
    # 设置默认虚拟机
    # --------------------------
    def setDefaultVM(self, vmId, vmName=None):  # 设置默认虚拟机
        print "设置默 虚拟机 id  ", vmId
        self.addOption("defaultVM", "id", vmId)
        print self.changeSectionValue("defaultVM", "id", vmId)

    # 获取默认虚拟机
    def getDefaultVM(self):  # 获取默认虚拟机
        return self.getValue("defaultVM", "id")

    # --------------------------
    # 设置自动登录 标记
    # flag == True  设置自动登录
    # flag == False 取消自动登录
    # --------------------------
    def setAutoLoginFlag(self, flag=False):
        if flag == True:
            self.changeSectionValue("autologin", "flag", "YES")
        else:
            self.changeSectionValue("autologin", "flag", "NO")

    # --------------------------
    # 判断是否是自动登录
    # return True  自动登录
    # return False  不是自动登录
    # --------------------------
    def isAutoLogin(self):
        if self.getValue("autologin", "flag") == "YES":
            return True
        else:
            return False


################################################
#  单元测试
################################################
if __name__ == "__main__":
    from os import environ
    import os

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

    conf = UserInfoConfFile()  # 实例化
    # 平台操作
    # conf.addCenter("192.168.102.33:8080", "济南平台")  # 添加平台
    # conf.addCenter("192.168.102.34:8080", "北京平台")  # 添加平台
    # conf.addCenter("192.168.102.55:8080", "上海平台")  # 添加平台
    # conf.setDefaultCenter("192.168.102.33:8080")  # 设置默认平台
    # print conf.getDefaultCenter()  # 获取默认平台
    # conf.deleteCenter("192.168.102.33:8080")
    # # conf.deleteCenter("192.168.102.55")
    # # conf.setUserLoginInfo("jxm","123456")               # 存储用户名密码
    # # print conf.getUserLoginInfo()                       # 获取用户名密码
    #
    # conf.setRememberUserInfoFlag(True)
    # print "---"
    # print conf.isRememberUserInfo()

    # conf.setDefaultVM("123456")
