import subprocess
from enum import Enum

from app.config import ALERTS_DIR, MAIN_SCRIPT


class ManagedServersApiException(Exception):
    def __init__(self, message):
        super().__init__()
        self.message = message


class Service(Enum):
    DISK = "disk_root", "root_disk_check.data"
    BACKUP_DISK = "disk_backup", "backup_disk_check.data"
    CPU_LOAD = "cpu_load", "cpu_load_check.data"
    PUPPET = "puppet", "puppet_check.data"
    SMTP = "smtp", "smtp_check.data"
    SPAMD = "spamd", "spamd_check.data"
    MEMORY = "memory", "free_memory_check.data"
    IMAP = "imap", "imap_check.data"
    POP = "pop", "pop_check.data"
    CSF = "csf", "csf_check.data"
    CP_LICENSE = "cp_license", "cplicense_check.data"
    HOSTNAME_DNS = "dns_query", "dns_query_check.data"
    FTP = "ftp", "ftp_check.data"
    BACKUP_AGE = "backup_age", "backup_age_check.data"
    SWAP = "swap", "swap_check.data"

    @property
    def background_data_dir(self):
        cmd = f"source {ALERTS_DIR}/{MAIN_SCRIPT}; echo -n $BACKGROUND_DATA/;"
        cmd_result = subprocess.Popen(
            [cmd],
            shell=True,
            stdout=subprocess.PIPE,
            universal_newlines=True,
        ).communicate()[0]
        return cmd_result

    @property
    def background_data(self):
        return f"{self.background_data_dir}{self.value[1]}"

    @property
    def codename(self):
        return self.value[0]

    @property
    def auto_fix_script(self):
        return f"{self.codename}_check"

    @staticmethod
    def is_mail_service(codename: str) -> bool:
        item_list = [i for i in Service if i.codename == codename]

        return bool(item_list) and item_list[0] in [
            Service.SMTP,
            Service.IMAP,
            Service.POP,
        ]


class AutoFixStatus(Enum):
    SUCCESS = "success", "The issue has been fixed automatically"
    FAILURE = "failure", "The issue has not been fixed automatically"
    PROCESS_MANUALLY = "N/A", "This issue should be checked manually"
    NO_AUTO_FIX = "no_auto_fix", "There is no autofix for this issue"

    @property
    def codename(self):
        return self.value[0]

    @property
    def description(self):
        return self.value[1]
