/* BdfServer - Copyright (c) 2010-2023 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.impl;

import fr.exemole.bdfserver.api.managers.SqlExportManager;
import fr.exemole.bdfserver.api.storage.SqlExportStorage;
import java.util.AbstractList;
import java.util.Collections;
import java.util.List;
import java.util.RandomAccess;
import java.util.SortedMap;
import java.util.TreeMap;
import net.fichotheque.exportation.sql.SqlExportDef;


/**
 *
 * @author Vincent Calame
 */
class SqlExportManagerImpl implements SqlExportManager {

    private final static List<SqlExportDef> EMPTY_LIST = Collections.emptyList();
    private final SqlExportStorage sqlExportStorage;
    private final SortedMap<String, SqlExportDef> sqlExportDefMap = new TreeMap<String, SqlExportDef>();
    private List<SqlExportDef> sqlExportDefList = EMPTY_LIST;

    SqlExportManagerImpl(SqlExportStorage sqlExportStorage) {
        this.sqlExportStorage = sqlExportStorage;
    }

    synchronized void check(List<SqlExportDef> sqlExportDefList) {
        sqlExportDefMap.clear();
        for (SqlExportDef scrutariExportDef : sqlExportDefList) {
            sqlExportDefMap.put(scrutariExportDef.getName(), scrutariExportDef);
        }
        updateList();
    }

    @Override
    public List<SqlExportDef> getSqlExportDefList() {
        return sqlExportDefList;
    }

    @Override
    public SqlExportDef getSqlExportDef(String name) {
        return sqlExportDefMap.get(name);
    }

    @Override
    public synchronized void putSqlExportDef(SqlExportDef sqlExportDef) {
        String name = sqlExportDef.getName();
        sqlExportDefMap.put(name, sqlExportDef);
        updateList();
        sqlExportStorage.saveSqlExportDef(sqlExportDef);
    }

    @Override
    public synchronized void removeSqlExportDef(String name) {
        boolean here = sqlExportDefMap.containsKey(name);
        if (!here) {
            return;
        }
        sqlExportDefMap.remove(name);
        sqlExportStorage.removeSqlExportDef(name);
        updateList();
    }

    private void updateList() {
        this.sqlExportDefList = new SqlExportDefList(sqlExportDefMap.values().toArray(new SqlExportDef[sqlExportDefMap.size()]));
    }


    private static class SqlExportDefList extends AbstractList<SqlExportDef> implements RandomAccess {

        private final SqlExportDef[] array;

        private SqlExportDefList(SqlExportDef[] array) {
            this.array = array;
        }

        @Override
        public int size() {
            return array.length;
        }

        @Override
        public SqlExportDef get(int index) {
            return array[index];
        }

    }

}
