/* BdfServer - Copyright (c) 2024 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.tools.storage;

import fr.exemole.bdfserver.api.storage.StorageContent;
import java.io.File;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;


/**
 *
 * @author Vincent Calame
 */
public abstract class StorageUnitBuilder {

    private final Map<String, StorageContent> storageContentMap;

    protected StorageUnitBuilder(boolean sort) {
        if (sort) {
            storageContentMap = new TreeMap<String, StorageContent>();
        } else {
            storageContentMap = new LinkedHashMap<String, StorageContent>();
        }
    }

    public StorageUnitBuilder addStorageContent(StorageContent storageContent) {
        storageContentMap.put(storageContent.getPath(), storageContent);
        return this;
    }

    public StorageUnitBuilder addStorageContent(String path, File file) {
        return addStorageContent(StorageUtils.toStorageContent(path, file));
    }

    public StorageUnitBuilder addStorageContent(String path, String text) {
        storageContentMap.put(path, StorageUtils.toStorageContent(path, text));
        return this;
    }

    public StorageUnitBuilder addStorageContent(String path, byte[] array) {
        storageContentMap.put(path, StorageUtils.toStorageContent(path, array));
        return this;
    }

    public StorageUnitBuilder populate(File dir, String pathRoot) {
        String path = pathRoot + dir.getName() + "/";
        for (File f : dir.listFiles()) {
            if (f.isDirectory()) {
                populate(f, path);
            } else {
                String filePath = path + f.getName();
                addStorageContent(filePath, f);
            }
        }
        return this;
    }

    public List<StorageContent> toStorageContentList() {
        return StorageUtils.wrap(storageContentMap.values().toArray(new StorageContent[storageContentMap.size()]));
    }

}
