# -*- coding: utf-8 -*-
# Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
import pathlib
import traceback

import utils.common.log as logger
from utils.common.exception import HCCIException
from utils.common.message import Message
from utils.common.ssh_util import Ssh
from utils.common.fic_base import StepBaseInterface
from utils.common.software_package_util import find_software_package
from plugins.DistributedStorage.common.base import TestCase
from plugins.DistributedStorage.common.parameter_gain import ParamsGain
from plugins.DistributedStorage.logic.install_operate import InstallOperate
from plugins.DistributedStorage.utils.common.deploy_constant import DeployConstant


class DeletePkgInf(StepBaseInterface):
    def __init__(self, project_id, pod_id, regionid_list=None, suit_id=None):
        super(DeletePkgInf, self).__init__(project_id, pod_id, regionid_list)
        self.project_id = project_id
        self.pod_id = pod_id
        self.regionid_list = regionid_list
        self.suit_id = suit_id
        self.err_code = 621021
        self.fs_args = ParamsGain(project_id, pod_id, regionid_list).get_args(suit_id)
        self.delete_pkg = DeletePkgImp(self.project_id, self.pod_id, self.fs_args)

    def execute(self, project_id, pod_id, regionid_list=None, suit_id=None):
        logger.info('Start install Deploymanager Package')
        try:
            self.delete_pkg.procedure()
        except HCCIException as err:
            logger.error("Delete Package error:{}".format(traceback.format_exc()))
            return Message(500, err)
        except Exception as err:
            logger.error("Delete Package error:{}".format(traceback.format_exc()))
            return Message(500, HCCIException(self.err_code, str(err)))
        return Message()

    def rollback(self, project_id, pod_id, regionid_list=None, suit_id=None):
        """
        标准调用接口：执行回滚
        :param project_id:
        :param pod_id:
        :return:Message类对象
        """
        return Message()

    def retry(self, project_id, pod_id, regionid_list=None, suit_id=None):
        """
        标准调用接口：重试
        :return: Message类对象
        """
        return self.execute(self.project_id, self.pod_id, self.regionid_list, self.suit_id)


class DeletePkgImp(TestCase):
    def __init__(self, project_id, pod_id, fs_args):
        super(DeletePkgImp, self).__init__(project_id, pod_id)
        self.fs_args = fs_args
        self.admin_pwd = fs_args.get("password")
        self.error_code = 621023

    @classmethod
    def _delete_dir_and_pkg(cls, cmd, client):
        try:
            Ssh.ssh_send_command(client, cmd, "#", 60, 3)
        finally:
            Ssh.ssh_close(client)

    def get_dir_and_pkg_deleted(self):
        logger.info("Query the name of the deleted package and directory")
        failed_list = []
        dir_and_pkg_deleted_list = []
        for _, cur_pattern in DeployConstant.ONE_STEP_UPGRADE.items():
            pkg_dict, _ = find_software_package(cur_pattern, self.project_id)
            if not pkg_dict:
                failed_list.append(cur_pattern)
                continue
            cur_pkg = list(pkg_dict.keys())[0]
            dir_and_pkg_deleted_list.append(cur_pkg)
            if cur_pkg.find("SPH") >= 0:
                dir_and_pkg_deleted_list.append(pathlib.Path(pathlib.Path(cur_pkg).stem).stem)
        if failed_list:
            err_msg = "These packages{} do not exist in the pkg directory of the upgrade tool.".format(failed_list)
            logger.error(err_msg)
            raise HCCIException(self.error_code, err_msg)
        logger.info("Query result:{}".format(dir_and_pkg_deleted_list))
        return dir_and_pkg_deleted_list

    def delete_dir_and_pkg(self, dir_and_pkg_deleted_list):
        cmd = "rm -rf /root/{} /root/{} /root/{} " \
              "/root/OceanStor-Pacific_deploymanager_`uname -p`*".format(*dir_and_pkg_deleted_list)
        master_client = InstallOperate.create_ssh_root_client(
            self.fs_args.get("master_ip"),
            self.fs_args.get("master_username"),
            self.fs_args.get("master_password"),
            self.fs_args.get("master_root_pwd")
        )
        logger.info("Log in to the node{} and delete the package".format(self.fs_args.get("master_ip")))
        self._delete_dir_and_pkg(cmd, master_client)
        slaver_client = InstallOperate.create_ssh_root_client(
            self.fs_args.get("slaver_ip"),
            self.fs_args.get("slaver_username"),
            self.fs_args.get("slaver_password"),
            self.fs_args.get("slaver_root_pwd")
        )
        logger.info("Log in to the node{} and delete the package".format(self.fs_args.get("slaver_ip")))
        self._delete_dir_and_pkg(cmd, slaver_client)

    def procedure(self):
        logger.info("Start to delete the package")
        dir_and_pkg_deleted_list = self.get_dir_and_pkg_deleted()
        self.delete_dir_and_pkg(dir_and_pkg_deleted_list)
        logger.info("Deleted successfully.")
