/* BdfServer_DirectoryStorage - 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.storage.directory.implementations;

import fr.exemole.bdfserver.api.storage.BdfStorageException;
import fr.exemole.bdfserver.api.storage.PasswordStorage;
import fr.exemole.bdfserver.storage.directory.StorageDirectory;
import fr.exemole.bdfserver.storage.directory.bdfdata.BdfdataStorageFileCatalog;
import fr.exemole.bdfserver.tools.storage.StorageFile;
import fr.exemole.bdfserver.tools.storage.StorageUtils;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 *
 * @author Vincent Calame
 */
public class PasswordStorageImpl implements PasswordStorage {

    private final StorageDirectory bdfdataDirectory;

    public PasswordStorageImpl(StorageDirectory bdfdataDirectory) {
        this.bdfdataDirectory = bdfdataDirectory;
    }

    @Override
    public String[] getPasswordArray() {
        List<String> result = new ArrayList<String>();
        List<String> lines = BdfdataStorageFileCatalog.password(bdfdataDirectory).readLines();
        if (lines != null) {
            for (String line : lines) {
                int idx = line.indexOf(':');
                if (idx < 1) {
                    continue;
                }
                if (idx == (line.length() - 1)) {
                    continue;
                }
                String passwordKey = line.substring(0, idx);
                String passwordValue = line.substring(idx + 1);
                result.add(passwordKey);
                result.add(passwordValue);
            }
        }
        return result.toArray(new String[result.size()]);
    }

    @Override
    public void savePasswordArray(String[] passwordArray) {
        StorageFile passwordStorageFile = BdfdataStorageFileCatalog.password(bdfdataDirectory);
        try (BufferedWriter writer = passwordStorageFile.getWriter()) {
            StorageUtils.writePasswordArray(writer, passwordArray);
        } catch (IOException ioe) {
            throw new BdfStorageException(ioe);
        }
    }

}
