/* BdfServer_Email - Copyright (c) 2011-2025 Vincent Calame - Exemole
 * Logiciel libre donné sous triple licence :
 * 1) selon les termes de la CeCILL V2
 * 2) selon les termes de l’EUPL V.1.1
 * 3) selon les termes de la GNU GPLv3
 * Voir le fichier licences.txt
 */


package fr.exemole.bdfserver.email;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.mapeadores.util.annotation.Nullable;
import net.mapeadores.util.ini.IniParser;
import net.mapeadores.util.smtp.SmtpParameters;
import net.mapeadores.util.smtp.SmtpUtils;
import net.mapeadores.util.text.StringUtils;


/**
 *
 * @author Vincent Calame
 */
public class SmtpManager {

    public final static short INIT_OK = 1;
    public final static short INIT_NOFILE = -1;
    public final static short INIT_IOEXCEPTION = -2;
    public final static short INIT_PROPERTIESERRORS = - 3;
    private final File iniFile;
    private List<String> errorList = StringUtils.EMPTY_STRINGLIST;
    private SmtpParameters smtpParameters;
    private short initState;

    public SmtpManager(@Nullable File iniFile) {
        this.iniFile = iniFile;
        init();
    }

    public boolean isInit() {
        return (initState == INIT_OK);
    }

    public short getInitState() {
        return initState;
    }

    public List<String> getErrorList() {
        return errorList;
    }

    public SmtpParameters getSmtpParameters() {
        return smtpParameters;
    }

    public String getIniFilePath() {
        if (iniFile == null) {
            return "";
        } else {
            return iniFile.getAbsolutePath();
        }
    }

    private void init() {
        if ((iniFile == null) || (!iniFile.exists()) || (iniFile.isDirectory())) {
            initState = INIT_NOFILE;
            smtpParameters = null;
            return;
        }
        Map<String, String> map = new HashMap<String, String>();
        try (FileInputStream is = new FileInputStream(iniFile)) {
            IniParser.parseIni(is, map);
        } catch (IOException ioe) {
            initState = INIT_IOEXCEPTION;
            smtpParameters = null;
            errorList = Collections.singletonList(ioe.getMessage());
        }
        if (map.isEmpty()) {
            initState = INIT_NOFILE;
            smtpParameters = null;
            return;
        }
        List<String> newErrorList = new ArrayList<String>();
        smtpParameters = SmtpUtils.toSmtpParameters(map, newErrorList);
        if (!newErrorList.isEmpty()) {
            smtpParameters = null;
            initState = INIT_PROPERTIESERRORS;
            errorList = newErrorList;
        } else {
            initState = INIT_OK;
        }
    }


}
