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

import fr.cenra.rhomeo.RhomeoTestCase;
import fr.cenra.rhomeo.api.Version;
import fr.cenra.rhomeo.core.CSVEncoder;
import fr.cenra.rhomeo.core.RhomeoCore;
import fr.cenra.rhomeo.core.preferences.ftp.FTPPreferences;

import java.beans.IntrospectionException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import javafx.concurrent.Task;
import javafx.embed.swing.JFXPanel;
import org.apache.commons.net.ftp.FTPClient;
import org.geotoolkit.nio.IOUtilities;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

/**
 *
 * @author Alexis Manin (Geomatys)
 */
public class ReferenceManagerTest extends RhomeoTestCase {

    @Autowired
    FTPPreferences prefs;

    @Autowired
    MockReferenceDescription desc;

    @Test
    public void testLists() throws Exception {
        new JFXPanel().setVisible(false);// necessary to init fx toolkit
        final FTPClient ftpClient = prefs.getAccess(FTPPreferences.ACCESS_POINTS.REFERENCES).createClient();

        ftpClient.makeDirectory(desc.getName());
        final String pathname = Paths.get(desc.getName()).resolve("1.0.1.csv").toString();

        // Create a new version on distant repository.
        final List<MockReference> refs;
        final Path tmpFile = Files.createTempFile("tmpVersion", ".csv");
        try {
            refs = createMockList(tmpFile);
            try (final InputStream stream = Files.newInputStream(tmpFile)) {
                ftpClient.storeFile(pathname, stream);
            }
        } finally {
            Files.delete(tmpFile);
        }

        // Clear local test data.
        IOUtilities.deleteRecursively(RhomeoCore.REFERENCE_PATH.resolve(desc.getName()));

        ReferenceManager<MockReference> manager = ReferenceManager.getOrCreate(desc);
        Task<ReferenceManager> t = manager.refresh();
        t.run();
        t.get();

        final Set<Version> distantVersions = manager.getDistantVersions();
        Assert.assertNotNull("Distant version list", distantVersions);
        Assert.assertFalse("Distant version list should not be empty.", distantVersions.isEmpty());

        final Set<Version> localVersions = manager.getInstalledVersions();
        Assert.assertNotNull("List of installed versions", localVersions);
        Assert.assertTrue("List of installed versions should be empty", localVersions.isEmpty());

        // Install found version
        final Version newVersion = distantVersions.iterator().next();
        t = manager.install(newVersion);
        t.run();
        t.get();
        Assert.assertTrue("installed version set should be updated on new version install.", localVersions.contains(newVersion));

        // Read data into downloaded version
        final List<MockReference> values = manager.getValues(newVersion);
        Assert.assertEquals("Loaded values are different from created ones !", refs, values);

        // Remove newly installed
        t = manager.uninstall(newVersion);
        t.run();
        t.get();
        Assert.assertFalse("Local version set should be updated when a version is deleted.", localVersions.contains(newVersion));

        // delete distant version
        ftpClient.deleteFile(pathname);
        t = manager.refresh();
        t.run();
        t.get();
        Assert.assertFalse("Distant version list has not been updated", distantVersions.contains(newVersion));
    }

    private static List<MockReference> createMockList(final Path toWriteInto) throws IOException, IntrospectionException {
        final CSVEncoder<MockReference> encoder = new CSVEncoder<>(toWriteInto, MockReference.class);

        final ArrayList<MockReference> list = new ArrayList<>();
        MockReference ref = new MockReference();
        ref.setFirst("toto");
        ref.setSecond(ZonedDateTime.now());
        ref.setThird(0.13);
        ref.setFourth(true);
        ref.setFifth(Float.NaN);
        list.add(ref);

        ref = new MockReference();
        ref.setFirst("tata");
        ref.setSecond(ZonedDateTime.now());
        ref.setThird(100.2);
        ref.setFourth(true);
        ref.setFifth(9.3f);
        list.add(ref);

        encoder.encode(list, true);

        return Collections.unmodifiableList(list);
    }
}
