/**
 * 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.result;

import com.fasterxml.jackson.databind.ObjectMapper;
import fr.cenra.rhomeo.api.data.Site;
import fr.cenra.rhomeo.api.process.Indicator;
import fr.cenra.rhomeo.api.result.DashboardResultItem;
import fr.cenra.rhomeo.api.result.Index;
import fr.cenra.rhomeo.core.RhomeoCore;
import fr.cenra.rhomeo.core.RhomeoRuntimeException;
import fr.cenra.rhomeo.core.Session;
import fr.cenra.rhomeo.core.util.ExportUtils;
import fr.cenra.rhomeo.core.util.GeometryUtils;
import fr.cenra.rhomeo.core.data.site.SiteRepository;
import fr.cenra.rhomeo.core.util.SerializableDataContext;
import java.beans.IntrospectionException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.logging.Level;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.sis.storage.DataStoreException;
import org.apache.sis.util.collection.IntegerList;
import org.geotoolkit.nio.IOUtilities;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Component in charge of storing indicator results locally.
 *
 * @author Alexis Manin (Geomatys)
 */
@Component
public class ResultStorage {

    @Autowired
    private ResultWriter writer;

    @Autowired
    private Session session;

    @Autowired
    private SiteRepository siteRepo;

    @Autowired
    private ResultWriter resultWriter;

    final String[] expectedFiles = new String[]{ExportUtils.METADATA_JSON, ResultWriter.RESULT_FILE_NAME, ResultWriter.ADDITIONAL_RESULT_FILE_NAME};

    private ResultStorage() {
        Arrays.sort(expectedFiles);
    }

    public void store() throws IOException, IntrospectionException {
        if (session.getResults() == null || session.getResults().isEmpty() || session.getDataContext() == null)
            return;

        final String sha1 = GeometryUtils.getSha1(session.getDataContext().getSite().getGeometry());
        final Path root = RhomeoCore.RESULT_PATH.resolve(sha1);
        Files.createDirectories(root);

        /* Sort results by indicator and year, as publication / export via dashboard
         * has to be able to export results only for a specific indicator at a
         * specific year. We iterate on indices and not on the tracking points
         * related to process context, because some protocols appear to use no
         * tracking point at all.
         */
        final IntegerList years = new IntegerList(10, Short.MAX_VALUE);
        for (final Index i : session.getResults()) {
            if (years.occurrence(i.getYear()) < 1)
                years.add(i.getYear());
        }

        for (final Indicator indic : session.getProcessContext().getIndicators()) {
            final Path indicPath = root.resolve(indic.getName());
            Files.createDirectories(indicPath);
            for (final int year : years) {
                final Path yearPath = indicPath.resolve(Integer.toString(year));
                IOUtilities.deleteRecursively(yearPath);
                Files.createDirectory(yearPath);
                writer.prepareWriting(yearPath)
                        .writeMetadataJSON()
                        .writeResults((i) -> i.getYear() == year && i.getSpi().getIndicator().equals(indic));
            }
        }
    }

    /**
     * Notify the result storage manager that a site had its name changed.
     * @param oldSiteName
     * @param newSiteName
     * @throws IOException
     */
//    public void siteNameChanged(final String oldSiteName, final String newSiteName) throws IOException {
//        final Base64.Encoder encoder = Base64.getEncoder().withoutPadding();
//        String oldName = encoder.encodeToString(oldSiteName.getBytes(StandardCharsets.UTF_8));
//        final Path oldPath = RhomeoCore.RESULT_PATH.resolve(oldName);
//        if (!Files.exists(oldPath))
//            return; // Nothing to move
//
//        final String newName = encoder.encodeToString(newSiteName.getBytes(StandardCharsets.UTF_8));
//        Files.move(oldPath, RhomeoCore.RESULT_PATH.resolve(newName));
//    }

    /**
     * Remove results associated to the input site, If any. Otherwise, do nothing.
     * @param siteName Name of the site to delete results for.
     *
     * @throws IOException If an error occurs while deleting files.
     */
    public void deleteIfExists(String siteName) throws IOException {
        if (siteName == null || (siteName = siteName.trim()).isEmpty())
            return;
        deleteIfExists(siteRepo.findOne(siteName));
    }

    /**
     * Remove results associated to the input site, If any. Otherwise, do nothing.
     * @param site The site to delete results for.
     *
     * @throws IOException If an error occurs while deleting files.
     */
    public void deleteIfExists(final Site site) throws IOException {
        if (site == null)
            return;
        final String sha1 = GeometryUtils.getSha1(site.getGeometry());
        IOUtilities.deleteRecursively(RhomeoCore.RESULT_PATH.resolve(sha1));
    }

    /**
     * Copy the results associated to the input dashboard item in the FTP pointed
     * by given client.
     *
     * Note : All files are uploaded on the current working directory of the FTP client.
     *
     * @param target Dashboard item to upload results for.
     * @param ftp Connection to the FTP.
     * @return true if we succeeded
     * @throws IOException
     */
    public boolean publish(final DashboardResultItem target, final FTPClient ftp) throws IOException {
        Optional<Path> directory = getDirectory(target);
        if (!directory.isPresent())
            return false;

        final Path root = directory.get();
        try {
            Files.list(root).forEach(p -> {
                final String fileName = p.getFileName().toString();
                if (Files.isRegularFile(p) && Arrays.binarySearch(expectedFiles, fileName) >= 0) {

                    try (final InputStream stream = Files.newInputStream(p)) {
                        ftp.storeFile(fileName, stream);
                    } catch (IOException e) {
                        throw new RhomeoRuntimeException(e);
                    }
                }
            });
        } catch (RhomeoRuntimeException e) {
            if (e.getCause() instanceof IOException) {
                throw (IOException) e.getCause();
            } else {
                throw e;
            }
        }
        return true;
    }

    /**
     * Publish results currently contained in the session into the current
     * working directory of the input client.
     *
     * @param ftpSupplier Provides an FTP client positioned in the directory we
     * want to send data to. The FTP CLient is closed internally.
     *
     * @throws IOException
     * @throws DataStoreException
     * @throws IntrospectionException
     */
    public void publish(final Supplier<FTPClient> ftpSupplier) throws IOException, DataStoreException, IntrospectionException {
        Path tmpDir = Files.createTempDirectory("results");
        try {
            resultWriter.prepareWriting(tmpDir).writeMetadataJSON().writeResults().writeAdditionalValues();

            final FTPClient ftp = ftpSupplier.get();
            try {
                Files.list(tmpDir).forEach(p -> {
                    final String fileName = p.getFileName().toString();
                    if (Files.isRegularFile(p)) {

                        try (final InputStream stream = Files.newInputStream(p)) {
                            if (!ftp.storeFile(fileName, stream))
                                throw new RhomeoRuntimeException("A file cannot be copied via FTP : ".concat(fileName));
                        } catch (IOException e) {
                            throw new RhomeoRuntimeException(e);
                        }
                    }
                });
            } finally {
                ftp.disconnect();
            }

        } catch (RhomeoRuntimeException e) {
            if (e.getCause() instanceof IOException) {
                throw (IOException) e.getCause();
            } else {
                throw e;
            }
        } finally {
            // If the task fails, it does not halt publication process.
            try {
                IOUtilities.deleteRecursively(tmpDir);
            } catch (Exception e) {
                RhomeoCore.LOGGER.log(Level.WARNING, "Cannot clear temporary data", e);
            }
        }
    }

    /**
     * Return a path to the CSV file containing main indices related to the
     * given dashboard item.
     * @param item
     * @return A path to the requested results, or an empty optional if there's
     * no result available, or they're not accessible.
     * @throws java.io.IOException If an error occurs while checking result path.
     */
    public Optional<Path> getMainResults(final DashboardResultItem item) throws IOException {
        Optional<Path> directory = getDirectory(item);
        if (directory.isPresent()) {

            final Path root = directory.get();
            // Read main results
            Path results = root.resolve(ResultWriter.RESULT_FILE_NAME);
            if (Files.isReadable(results)) {
                return Optional.of(results);
            }
        }

        return Optional.empty();
    }

    /**
     * Return a path to the CSV file containing additional indices related to
     * the given dashboard item.
     * @param item
     * @return A path to the requested results, or an empty optional if there's
     * no result available, or they're not accessible.
     * @throws java.io.IOException If an error occurs while checking result path.
     */
    public Optional<Path> getAdditionalResults(final DashboardResultItem item) throws IOException {
        Optional<Path> directory = getDirectory(item);
        if (directory.isPresent()) {

            final Path root = directory.get();
            // Read main results
            Path results = root.resolve(ResultWriter.ADDITIONAL_RESULT_FILE_NAME);
            if (Files.isReadable(results)) {
                return Optional.of(results);
            }
        }

        return Optional.empty();
    }

    public Optional<SerializableDataContext> readMetadata(final DashboardResultItem item) throws IOException {
        Optional<Path> directory = getDirectory(item);
        if (directory.isPresent()) {

            final Path root = directory.get();
            // Read main results
            Path results = root.resolve(ExportUtils.METADATA_JSON);
            if (Files.isReadable(results)) {
                try (final BufferedReader reader = Files.newBufferedReader(results, StandardCharsets.UTF_8)) {
                    return Optional.of(new ObjectMapper().readValue(reader, SerializableDataContext.class));
                }
            }
        }

        return Optional.empty();
    }

    private Optional<Path> getDirectory(final DashboardResultItem target) throws IOException {
        if (target.getSite() == null || target.getSite().isEmpty()
                || target.getIndicator() == null || target.getIndicator().isEmpty())
            return Optional.empty();

        final Site site = siteRepo.findOne(target.getSite());
        if (site == null)
            return Optional.empty();

        final String sha1 = GeometryUtils.getSha1(site.getGeometry());
        final Path root = RhomeoCore.RESULT_PATH.resolve(sha1).resolve(target.getIndicator()).resolve(Integer.toString(target.getYear()));
        if (!Files.isDirectory(root) || !Files.list(root).findAny().isPresent())
            return Optional.empty();

        return Optional.of(root);
    }
}
