#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
import re

from utils.common import log
from IPy import IP
from utils.common.exception import HCCIException
from utils.common.ssh_util2 import Ssh as SshUtil


def client_can_pinged_to(client, host, normal=True):
    """
    return the host can pinged to or not
    :param client: PingSSHclient object
    :param host: the host ip of the vm
    :return:
    True ---can be pinged to
    False ---can not be pinged to
    """
    import traceback
    import platform
    try:
        cmd = _get_ping_cmd(host)
    except Exception as e:
        log.error('try to get ping cmd by host: %s failed: %s' % (host, str(e)))
        log.error(traceback.format_exc())
    ping_times = _get_ping_times(normal)
    try:
        res = loop_ping_cmd(ping_times, client, cmd, host, platform)
    except Exception as e:
        log.error('try ping host:%s failed:%s' % (host, str(e)))
        log.error(traceback.format_exc())
    else:
        if res:
            return True
        return False
    no_pinged = None
    return no_pinged


def _get_ping_times(normal):
    if normal:
        ping_times = 3
    else:
        ping_times = 10
    return ping_times


def _get_ping_cmd(host):
    import platform
    if IP(host).version() == 6:
        ping_act = "ping6"
    else:
        ping_act = "ping"
    if platform.system() == 'Windows':
        cmd = '%s -w 1000 -n %d %s' % (ping_act, 3, host)
    else:
        cmd = '%s -W 1 -c %d %s' % (ping_act, 3, host)
    return cmd


def loop_ping_cmd(ping_times, client, cmd, host, platform):
    res = False
    for _ in range(0, ping_times):
        rsp = SshUtil.ssh_exec_command_return(client, cmd)
        log.info('localhost: %s,ping host:%s, rsp:%s' % (client.get("ip"), host, rsp))
        if platform.system() == 'Windows':
            if str(rsp).find('TTL=') >= 0:
                res = True
            else:
                continue
        else:
            if str(rsp).find('ttl=') >= 0:
                res = True
            else:
                continue
    return res


class ExecCmd:

    @classmethod
    def check_switch_root(cls, client, root_pwd):
        try:
            SshUtil.ssh_send_command(client, "su - root", "Password:", timeout=30)
        except HCCIException as e:
            log.error("[FSBR] Switch root fail. Not get expected output,detail: %s" % str(e))
            return False
        try:
            SshUtil.ssh_send_command(client, root_pwd, "#", timeout=30)
        except HCCIException as e:
            log.error("[FSBR] Switch root fail. Not get expected output,detail: %s" % str(e))
            return False
        return True

    @classmethod
    def check_language(cls, client):
        pattern = re.compile("zh_CN")
        cmd = "echo $LANG"
        try:
            resp = SshUtil.ssh_exec_command_return(client, cmd, retry_times=3)
        except HCCIException as e:
            log.error("[FSBR] Check language fail.detail: %s" % str(e))
            return False
        result = ''.join(resp)
        log.info("[FSBR] exec command success. detail:%s" % result)
        if pattern.findall(result):
            return False
        return True

    @classmethod
    def create_client(cls, host_ip, username, passwd):
        return SshUtil.ssh_create_client(host_ip, username, passwd)

    @classmethod
    def close_client(cls, client):
        SshUtil.ssh_close(client)
