import subprocess
from email_validator import validate_email, EmailNotValidError

from .config import getDockersConfig, getSecretConfig

sympa_user = getSecretConfig("sympaServ", "SOAP_USER")
sympa_pass = getSecretConfig("sympaServ", "SOAP_PASSWORD")
sympa_listmaster = getSecretConfig("sympaServ", "ADMINEMAIL")
sympa_url = f"https://{getDockersConfig('sympaHost')}.{getDockersConfig('domain')}"
sympa_soap = "docker exec -i sympaServ /usr/lib/sympa/bin/sympa_soap_client.pl"
sympa_domain = getDockersConfig('domain_sympa')
sympa_liste_info = "infos"


# docker exec -i sympaServ /usr/lib/sympa/bin/sympa_soap_client.pl --soap_url=${httpProto}://${URL_LISTE}/sympasoap --trusted_application=${sympa_SOAP_USER} --trusted_application_password=${sympa_SOAP_PASSWORD} --proxy_vars=\"USER_EMAIL=${LISTMASTER}\" --service=add --service_parameters=\"${NL_LIST},${EMAIL_SOUHAITE}\""  | tee -a "${CMD_SYMPA}"

class Sympa:

    def _execute_sympa_command(self, email, liste, service):
        if validate_email(email) and validate_email(liste):
            cmd = f'{sympa_soap} --soap_url={sympa_url}/sympasoap --trusted_application={sympa_user} --trusted_application_password={sympa_pass} --proxy_vars=USER_EMAIL={sympa_listmaster} --service={service} --service_parameters="{liste},{email}" && echo $?'
            output = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
            return output.decode()

    def add_email_to_list(self, email, liste=sympa_liste_info):
        """
        Ajouter un email dans une liste sympa
        """
        output = self._execute_sympa_command(email, f"{liste}@{sympa_domain}", 'add')
        return output

    def delete_email_from_list(self, email, liste=sympa_liste_info):
        """
        Supprimer un email dans une liste sympa
        """
        output = self._execute_sympa_command(email, f"{liste}@{sympa_domain}", 'del')
        return output



