import os
import subprocess
from logging_handler import LoggerHandler
from error_handler import ExportErrorMessages
from file_management_handler import FileManagementHandler


class ArchiveHandler:
    """
    class for handling Archive rules transfer

    """
    archive_rules_file_name = 'archive_rules.json'
    @staticmethod
    def is_archive_active():
        LoggerHandler.print_message('is_archive_active')
        emadot_cmd = 'emadot.exe' if os.name == 'nt' else 'em -no_wrap adot'
        command = f'{emadot_cmd} -check AddOnName WA'

        try:
            process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True,
                                       universal_newlines=True)
            # Wait for the process to finish and capture the output
            stdout, stderr = process.communicate()

            # Check the return code to see if the process was successful
            return_code = process.returncode
            LoggerHandler.print_message("stdout:" + str(stdout))
            LoggerHandler.print_message(f"emadot return code: {return_code}")

            if return_code == 0:
                LoggerHandler.print_message('WA is activated')
                return True
            else:
                LoggerHandler.print_message('WA is not activated')
                return False
        except Exception as e:
            LoggerHandler.print_message("Error:" + str(e) + str(stdout) + str(stderr))
            raise Exception(
                f"{ExportErrorMessages.FAILED_TO_VERIFY_ARCHIVE_ADDON.value}" + str(e) + str(stdout) + str(stderr))




    @staticmethod
    def export_archive_rules(em_export_directory, aapi_url, aapi_credentials):
        """
        This method export archive rules via aapi
        :return:
        """
        command = f'ctm env delete emexport'
        LoggerHandler.print_message(command)
        try:
            process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True,
                                       universal_newlines=True)
            # Wait for the process to finish and capture the output
            stdout, stderr = process.communicate()

            # Check the return code to see if the process was successful
            return_code = process.returncode
            LoggerHandler.print_message("stdout:" + str(stdout))
            LoggerHandler.print_message(f"ctm env delete return code: {return_code}")

            if return_code == 0:
                LoggerHandler.print_message('ctm env delete is OK')
            else:
                LoggerHandler.print_message('ctm env delete is not OK')
                raise Exception(ExportErrorMessages.FAILED_TO_DELETE_AAPI_CLI_ENV.value)
        except Exception as e:
            LoggerHandler.print_message("Info:" + str(e) + str(stdout) + str(stderr))


        command = f'ctm environment add emexport {aapi_url} {aapi_credentials.replace("/", " ")}'
        LoggerHandler.print_message(f'ctm environment add emexport {aapi_url}')
        try:
            process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True,
                                       universal_newlines=True)
            # Wait for the process to finish and capture the output
            stdout, stderr = process.communicate()

            # Check the return code to see if the process was successful
            return_code = process.returncode
            LoggerHandler.print_message("stdout:" + str(stdout))
            LoggerHandler.print_message(f"ctm environment add return code: {return_code}")

            if return_code == 0:
                LoggerHandler.print_message('ctm environment is activated')
            else:
                LoggerHandler.print_message('ctm environment is not activated')
                raise Exception(ExportErrorMessages.FAILED_TO_CREATE_AAPI_CLI_ENV.value)
        except Exception as e:
            LoggerHandler.print_message("Error:" + str(e) + str(stdout) + str(stderr))
            raise Exception(
                f"{ExportErrorMessages.FAILED_TO_CREATE_AAPI_CLI_ENV.value}" + str(e) + str(stdout) + str(stderr))

        command = f'ctm session login -e emexport'
        LoggerHandler.print_message(command)
        try:
            process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True,
                                       universal_newlines=True)
            # Wait for the process to finish and capture the output
            stdout, stderr = process.communicate()

            # Check the return code to see if the process was successful
            return_code = process.returncode
            LoggerHandler.print_message("stdout:" + str(stdout))
            LoggerHandler.print_message(f"ctm session login return code: {return_code}")

            if return_code == 0:
                LoggerHandler.print_message('ctm session login is OK')
            else:
                LoggerHandler.print_message('ctm session login is not OK')
                raise Exception(ExportErrorMessages.FAILED_TO_LOGIN_AAPI_CLI_ENV.value)
        except Exception as e:
            LoggerHandler.print_message("Error:" + str(e) + str(stdout) + str(stderr))
            raise Exception(
                f"{ExportErrorMessages.FAILED_TO_LOGIN_AAPI_CLI_ENV.value}" + str(e) + str(stdout) + str(stderr))

        command = f'ctm config archive:rules::get'
        LoggerHandler.print_message(command)
        try:
            process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True,
                                       universal_newlines=True)
            # Wait for the process to finish and capture the output
            stdout, stderr = process.communicate()

            # Check the return code to see if the process was successful
            return_code = process.returncode

            LoggerHandler.print_message("stdout:" + str(stdout))
            LoggerHandler.print_message(f"ctm config archive:rules::get return code: {return_code}")

            if return_code == 0:
                LoggerHandler.print_message('ctm config archive:rules::get is OK')
            else:
                LoggerHandler.print_message('ctm config archive:rules::get is not OK')
                raise Exception(ExportErrorMessages.FAILED_TO_GET_ARCHIVE_RULES_VIA_AAPI.value)

        except Exception as e:
            LoggerHandler.print_message("Error:" + str(e) + str(stdout) + str(stderr))
            raise Exception(
                f"{ExportErrorMessages.FAILED_TO_GET_ARCHIVE_RULES_VIA_AAPI.value}" + str(e) + str(stdout) + str(stderr))

        FileManagementHandler.create_file(em_export_directory, ArchiveHandler.archive_rules_file_name, str(stdout))
        if not os.path.exists(os.path.join(em_export_directory, ArchiveHandler.archive_rules_file_name)):
            raise Exception(ExportErrorMessages.FAILED_TO_CREATE_ARCHIVE_RULES_FILE.value)

        command = f'ctm env delete emexport'
        LoggerHandler.print_message(command)
        try:
            process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True,
                                       universal_newlines=True)
            # Wait for the process to finish and capture the output
            stdout, stderr = process.communicate()

            # Check the return code to see if the process was successful
            return_code = process.returncode
            LoggerHandler.print_message("stdout:" + str(stdout))
            LoggerHandler.print_message(f"ctm env delete return code: {return_code}")

            if return_code == 0:
                LoggerHandler.print_message('ctm env delete is OK')
            else:
                LoggerHandler.print_message('ctm env delete is not OK')
                raise Exception(ExportErrorMessages.FAILED_TO_DELETE_AAPI_CLI_ENV.value)
        except Exception as e:
            LoggerHandler.print_message("Error:" + str(e) + str(stdout) + str(stderr))

