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

import fr.cenra.rhomeo.core.data.site.SiteRepository;
import fr.cenra.rhomeo.core.data.site.DuplicatedKeyException;
import fr.cenra.rhomeo.core.data.site.SiteRepositoryImpl;
import fr.cenra.rhomeo.RhomeoTestCase;
import fr.cenra.rhomeo.api.IdentifiedObject;
import fr.cenra.rhomeo.api.data.Site;
import fr.cenra.rhomeo.core.RhomeoCore;
import fr.cenra.rhomeo.core.data.site.SiteImpl;
import javafx.collections.ObservableList;
import org.apache.sis.storage.DataStoreException;
import org.geotoolkit.data.FeatureReader;
import org.geotoolkit.data.query.QueryBuilder;
import org.geotoolkit.data.shapefile.ShapefileFeatureStore;
import org.junit.Test;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import org.apache.sis.test.DependsOnMethod;
import org.geotoolkit.nio.IOUtilities;
import org.junit.AfterClass;

import static org.junit.Assert.*;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Test reading / writing methods using the {@link SiteRepository} API.
 *
 * @author Cédric Briançon (Geomatys)
 */
public class SiteRepositoryTest extends RhomeoTestCase {

    /**
     * Mock SHP in the resources.
     */
    public static final String RESOURCES_DATA_SHP = "sites.shp";

    @Autowired
    SiteRepository repo;

    /**
     * Remove tests path for sites SHP.
     *
     * @throws IOException
     */
    @AfterClass
    public static void finalization() throws IOException {
        IOUtilities.deleteRecursively(RhomeoCore.SITES_PATH);
    }

    /**
     * Verify method {@link SiteRepository#findAll()}.
     */
    @Test
    public void findAllTest() {
        final ObservableList<String> sites = repo.findNames();
        assertNotNull(sites);
        assertTrue(sites.isEmpty());
    }

    /**
     * Verify method {@link SiteRepository#create(IdentifiedObject)} and {@link SiteRepository#delete(String)}.
     *
     * @throws MalformedURLException
     * @throws DataStoreException
     * @throws DuplicatedKeyException
     */
    @DependsOnMethod("findAllTest")
    @Test
    public void createDeleteTest() throws MalformedURLException, DataStoreException, DuplicatedKeyException, URISyntaxException {
        try (final ShapefileFeatureStore testDataStore = new ShapefileFeatureStore(this.getClass().getResource(RESOURCES_DATA_SHP).toURI(), "no namespace");
             final FeatureReader reader = testDataStore.getFeatureReader(QueryBuilder.all(testDataStore.getName()))) {

            assertTrue(reader.hasNext());

            final Site newSite = SiteRepositoryImpl.toSite(reader.next());
            repo.create(newSite);

            final ObservableList<String> allSites = repo.findNames();
            assertNotNull(allSites);
            assertEquals(1, allSites.size());

            repo.delete(newSite.getName());
            assertTrue(allSites.isEmpty());
        }
    }


    /**
     * Ensures {@link SiteRepository#findOne(String)} works fine.
     *
     * @throws IOException
     * @throws DataStoreException
     */
    @DependsOnMethod("createDeleteTest")
    @Test
    public void getSiteTest() throws Exception {
        try (final ShapefileFeatureStore testDataStore = new ShapefileFeatureStore(this.getClass().getResource(RESOURCES_DATA_SHP).toURI(), "no namespace");
             final FeatureReader reader = testDataStore.getFeatureReader(QueryBuilder.all(testDataStore.getName()))) {

            final Site newSite = SiteRepositoryImpl.toSite(reader.next());
            repo.create(newSite);

            final Site addedSite = repo.findOne(newSite.getName());
            assertNotNull(addedSite);
            assertEquals(newSite, addedSite);
            assertEquals(newSite.getCountyCode(), addedSite.getCountyCode());

            repo.delete(newSite.getName());
        }
    }

    /**
     * Verify method {@link SiteRepository#update(IdentifiedObject)}}.
     *
     * @throws MalformedURLException
     * @throws DataStoreException
     * @throws DuplicatedKeyException
     */
    @DependsOnMethod("getSiteTest")
    @Test
    public void updateTest() throws MalformedURLException, DataStoreException, DuplicatedKeyException, URISyntaxException {
        try (final ShapefileFeatureStore testDataStore = new ShapefileFeatureStore(this.getClass().getResource(RESOURCES_DATA_SHP).toURI(), "no namespace");
             final FeatureReader reader = testDataStore.getFeatureReader(QueryBuilder.all(testDataStore.getName()))) {

            final Site newSite = SiteRepositoryImpl.toSite(reader.next());
            repo.create(newSite);

            final String testOrtho = "test orthoptere";
            ((SiteImpl)newSite).setOrthoptereType(testOrtho);
            repo.update(newSite);

            final Site updatedSite = repo.findOne(newSite.getName());
            assertNotNull(updatedSite.getOrthoptereType());
            assertEquals(testOrtho, updatedSite.getOrthoptereType());
            assertEquals(newSite.getOrthoptereType(), updatedSite.getOrthoptereType());

            ((SiteImpl)updatedSite).setName("myNewName");
            repo.create(updatedSite);

            try {
                repo.update(updatedSite, newSite.getName());
            } catch (DuplicatedKeyException e) {
                // expected behavior
            }

            repo.delete(newSite.getName());
            repo.delete(updatedSite.getName());
        }
    }
}
