# -*- coding: utf-8 -*-
import time
import datetime
from copy import deepcopy
import utils.common.log as logger
from plugins.DistributedStorage.common.base import TestCase
from utils.business.manageone_util2 import ManageOneUtil2


class RegAccountToUnifyPwd(TestCase):
    def __init__(self, project_id, pod_id, fs_args):
        super().__init__(project_id, pod_id)
        self.fs_args = fs_args
        self.manage_one_opr = ManageOneUtil2()

    def procedure(self):
        """
        获取待注册账号信息 -> 组装账户唯一标识信息 -> 调用uniform_password_util注册
        """
        logger.info('Query register nodes account info')
        reg_accounts_info = self.get_account_data()
        logger.info('Query nodes info account successfully')
        if reg_accounts_info:
            logger.info('Registering account to manage one')
            for account in reg_accounts_info:
                logger.info('Registering account to manage one')
                self.reg_account_to_unify_pwd(account)
                logger.info('The account is registered successfully: [ip:{}]'
                            .format(account.get('ip_value')))
        logger.info('All accounts are registered successfully')

    def get_account_data(self):
        """
        获取待注册账户信息
        """
        tag_list = ['master_{}', 'slaver_{}']
        account_list = []
        for tag in tag_list:
            general_account_info = {'ip_value': self.fs_args.get(tag.format('ip')),
                                    'user': self.fs_args.get(tag.format('username')),
                                    'pwd': self.fs_args.get(tag.format('password'))}
            root_account_info = {'ip_value': self.fs_args.get(tag.format('ip')),
                                 'user': 'root',
                                 'pwd': self.fs_args.get(tag.format('root_pwd'))}
            account_list.extend([general_account_info, root_account_info])
            logger.info("Host[%s] general account info: user[%s], pwd:****" %
                        (general_account_info.get("ip_value"), general_account_info.get("user")))
            logger.info("Host[%s] root account info: user[%s], pwd:****" %
                        (root_account_info.get("ip_value"), root_account_info.get("user")))
        return account_list

    def reg_account_to_unify_pwd(self, account_info):
        """
        组装统一密码唯一标识信息，并注册
        """
        ip_value, user, pwd = account_info.get('ip_value'), account_info.get('user'), account_info.get('pwd')
        now_time = int(round(time.time() * 1000))
        expire_time = now_time + 90 * 24 * 3600 * 1000
        body = {
            "componentName": self.fs_args.get('component_name'),
            "ruleList": [],
            "subComponents": [
                {
                    "createdAccountList": [
                        {
                            "accountDescription": "{\"zh-cn\":\"登录账号\",\"en-us\":\"login account\"}",
                            "accountName": user,
                            "accountType": 1,
                            "lastPasswdChange": int(round(datetime.datetime.utcnow().timestamp() * 1000)),
                            # 获取系统当前UTC时间戳
                            "modifyType": 2,
                            "operationType": 0,
                            "ip": ip_value,
                            "passwd": pwd,
                            "passwdComplexity": {
                                "dcredit": 0,
                                "difok": 3,
                                "lcredit": 0,
                                "minlen": 8,
                                "ocredit": 0,
                                "passwdChangeMaxBetweenTime": 90,
                                "passwdChangeMinBetweenTime": 0,
                                "ucredit": 0
                            },
                            "passwdExpires": expire_time,
                            "region": self.fs_args.get("region_id"),
                            "relativeAccount": [],
                            "riskMessage": "{\"zh-cn\":\"此账号用户密码会过期，过期时间默认90天，请注意在过期时间前修改密码，"
                                           "否则无法登陆\",\"en-us\":\"This user’s password will expire, and the "
                                           "expiration time is 90 days by default. Please note that you can change "
                                           "the password before the expiration time, otherwise you cannot log in.\"}",
                            "usedScene": "Distributed storage"
                        }
                    ],
                    "subComponentName": self.fs_args.get("sub_component_name"),
                    "usedAccountList": []
                }
            ]
        }
        if user == 'root':
            body["subComponents"][0]["createdAccountList"][0]["passwdComplexity"]["passwdChangeMaxBetweenTime"] = 99999
            body["subComponents"][0]["createdAccountList"][0]["passwdExpires"] = -1
            body["subComponents"][0]["createdAccountList"][0]["accountDescription"] = ROOT_ACCOUNT_DES
            body["subComponents"][0]["createdAccountList"][0]["riskMessage"] = ROOT_RISK_MSG
        body_tmp = deepcopy(body)
        body_tmp["subComponents"][0]["createdAccountList"][0]['passwd'] = '***'
        logger.info('body:{}'.format(body_tmp))
        logger.info('starting to register account by interface')
        self.manage_one_opr.uniform_password_util(self.project_id, self.fs_args.get('region_id'), body)


ROOT_ACCOUNT_DES = \
    "{\"zh-cn\":\"操作系统管理员，用于登录虚拟机的操作系统，可以执行所有命令。考虑到对系统安全的影响，在登录节点时，" \
    "不能使用root帐号直接登录，需要使用普通帐号登录后通过执行命令su root切换为root帐号\",\"en-us\":\"The operating " \
    "system administrator is used to log in to the operating system of the virtual machine and can " \
    "execute all commands. Considering the impact on system security,When logging in to a node," \
    " you cannot use the root account to log in directly. You need to log in with a normal account " \
    "and switch to the root account by executing the command su root.\"}"
ROOT_RISK_MSG = \
    "{\"zh-cn\":\"密码不会过期，修改密码对业务暂无影响\", \"en-us\":\"The password will not expire, and changing " \
    "the password has no impact on the business temporarily.\"}"
