/**
 * Copyright © CENRA (2016)
 *
 * remi.clement@espaces-naturels.fr
 * 
 * This software is a multi-platform and portable application based on 
 * the scientifical toolbox to monitor wetlands. With this toolbox it’s 
 * possible to calculate indicators «RhoMéO» to monitor quality, 
 * fonctionalities and urban and agricultural pressures of wetlands. 
 * Indicators are calculated using naturalist data entered and/or imported,
 * and geographic data downloaded from a geographic server.
 * 
 * This software is governed by the CeCILL license under French law and
 * abiding by the rules of distribution of free software.  You can  use, 
 * modify and/ or redistribute the software under the terms of the CeCILL
 * license as circulated by CEA, CNRS and INRIA at the following URL
 * "http://www.cecill.info". 
 * 
 * As a counterpart to the access to the source code and  rights to copy,
 * modify and redistribute granted by the license, users are provided only
 * with a limited warranty  and the software's author,  the holder of the
 * economic rights,  and the successive licensors  have only  limited
 * liability. 
 * 
 * In this respect, the user's attention is drawn to the risks associated
 * with loading,  using,  modifying and/or developing or reproducing the
 * software by the user in light of its specific status of free software,
 * that may mean  that it is complicated to manipulate,  and  that  also
 * therefore means  that it is reserved for developers  and  experienced
 * professionals having in-depth computer knowledge. Users are therefore
 * encouraged to load and test the software's suitability as regards their
 * requirements in conditions enabling the security of their systems and/or 
 * data to be ensured and,  more generally, to use and operate it in the 
 * same conditions as regards security. 
 * 
 * The fact that you are presently reading this means that you have had
 * knowledge of the CeCILL license and that you accept its terms.
*/
package fr.cenra.rhomeo.core.preferences.ftp;

import fr.cenra.rhomeo.core.RhomeoCore;
import fr.cenra.rhomeo.core.preferences.net.NetPreferences;
import fr.cenra.rhomeo.core.util.SecretGenerator;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.prefs.Preferences;
import javax.annotation.PostConstruct;
import javax.validation.constraints.NotNull;
import org.apache.sis.util.ArgumentChecks;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

/**
 * Holds preferences over FTP connections. You can retrieve information about a
 * specific FTP connection by using {@link #getAccess(fr.cenra.rhomeo.core.preferences.ftp.FTPPreferences.ACCESS_POINTS)
 * }.
 *
 * Known connections are listed in {@link ACCESS_POINTS}.
 *
 * @author Alexis Manin (Geomatys)
 */
@Component
@Qualifier(FTPPreferencesImpl.NAME)
@Validated
public class FTPPreferencesImpl implements FTPPreferences {

    public static final String NAME = "FTPPreferencesImpl";

    private final Preferences root;

    public FTPPreferencesImpl() {
        root = Preferences.userNodeForPackage(FTPPreferencesImpl.class);
    }

    /**
     * DO NOT USE IT !
     *
     * @param key DO NOT USE IT !
     * @return DO NOT USE IT !
     */
    @Override
    public String getPreference(Object key) {
        throw new UnsupportedOperationException("No value stored on root.");
    }

    /**
     * DO NOT USE IT !
     *
     * @param key DO NOT USE IT !
     * @param value DO NOT USE IT !
     */
    @Override
    public void setPreference(Object key, String value) {
        throw new UnsupportedOperationException("No value stored on root.");
    }

    @Override
    public List getKeys() {
        return Collections.EMPTY_LIST;
    }

    /**
     * Give all information about a specific FTP end point.
     *
     * @param ap The FTP service to retrieve.
     *
     * @return an object capable to open a connection over the queried FTP
     * service.
     */
    @NotNull
    @Override
    public FTPAccess getAccess(@NotNull final ACCESS_POINTS ap) {
        ArgumentChecks.ensureNonNull("Input access point", ap);
        return new FTPAccess(root.node(ap.name()));
    }

    @Override
    public int getPriority() {
        return 0;
    }

    /**
     * If no FTP account has been parameterised, a default one is set for result
     * publication and reference data.
     */
    @PostConstruct
    private void checkDefaultAccesses() {
        FTPAccess results = getAccess(FTPPreferences.ACCESS_POINTS.RESULTS);
        if (setDefaultAccess(results)) {
            results.setWorkingDir("results");
        }

        FTPAccess references = getAccess(FTPPreferences.ACCESS_POINTS.REFERENCES);
        if (setDefaultAccess(references)) {
            references.setWorkingDir("references");
        }
    }

    private boolean setDefaultAccess(final FTPAccess access) {
        if ((access.getAdress() == null || access.getAdress().trim().isEmpty())
                && (access.getLogin() == null || access.getLogin().trim().isEmpty())
                && (access.getWorkingDir() == null || access.getWorkingDir().trim().isEmpty())) {

            access.setAdress("constellation.cenra-outils.org");
            access.setLogin("rhomeoftp");
            final SecretGenerator gen = SecretGenerator.getInstance().orElse(null);
            if (gen == null)
                return false;

            try {
                access.setPassword(gen.decrypt("4Iru5sD2uzixbWHhu7R72s658w/l3yCz", getDefaultKey(), getDefaultSR()));
                return true;
            } catch (IOException | GeneralSecurityException ex) {
                RhomeoCore.LOGGER.log(Level.WARNING, null, ex);
            }
        }
        return false;
    }

    private byte[] getDefaultKey() throws IOException {
        final byte[] buf = new byte[16];
        int read = 0;
        try (final InputStream stream = NetPreferences.class.getResourceAsStream("defaultKey")) {
            do {
                read += stream.read(buf, read, buf.length - read);
            } while (read < buf.length - 1);
        }

        return buf;
    }

    private byte[] getDefaultSR() throws IOException {
        final byte[] buf = new byte[8];
        int read = 0;
        try (final InputStream stream = NetPreferences.class.getResourceAsStream("defaultSR")) {
            do {
                read += stream.read(buf, read, 8 - read);
            } while (read < 7);
        }

        return buf;
    }
}
