/**
 * 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.core.CSVDecoder;
import fr.cenra.rhomeo.core.CSVEncoder;
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.security.MessageDigest;
import java.time.ZonedDateTime;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.sis.test.DependsOnMethod;
import org.apache.sis.test.TestCase;
import org.apache.sis.util.ArgumentChecks;
import org.geotoolkit.util.collection.CloseableIterator;
import org.junit.Assert;
import org.junit.Test;

/**
 *
 * @author Alexis Manin (Geomatys)
 */
public class CSVMappingTest extends TestCase {

    @Test
    public void encodeStringWithSeparatorTest() throws Exception {
        final MockReference ref = new MockReference();
        ref.setFirst("lalaleigni; apegnpgbpa,;\"n ebo\"; bfozb\";\"");
        ref.setFifth(Float.NaN);
        ref.setSecond(ZonedDateTime.now());

        final Path tmpFile = Files.createTempFile("stringWithSeparator", ".csv");
        try {
            new CSVEncoder(tmpFile, MockReference.class).encode(Collections.singleton(ref), true);
            final List decoded = new CSVDecoder(tmpFile, MockReference.class).decode();
            Assert.assertEquals("Decoded file should contain one unique element !", 1, decoded.size());
            Assert.assertEquals("Decoded object is not equal to the original one !", ref, decoded.get(0));
        } finally {
            Files.delete(tmpFile);
        }
    }

    /**
     * Create randomly filled instances of {@link MockReference}, then write them
     * in a CSV file. We then decode lazily, and reencode it immediately in another
     * file.
     *
     * To check procedure validity, we compare md5 hash of the two files written.
     *
     * @throws Exception
     */
    @DependsOnMethod("encodeStringWithSeparatorTest")
    @Test
    public void readWriteReferenceTest() throws Exception {
        // Check written content
        final MessageDigest digest = MessageDigest.getInstance("md5");

        final Path firstPass = Files.createTempFile("referenceIO", ".csv");
        final Path secondPass = Files.createTempFile("referenceIO", ".csv");
        try {
            final int count = (int) 1e2;
            new CSVEncoder(firstPass, MockReference.class).encode(new RefCreator(count), false);
            final byte[] md5 = computeDigest(digest, firstPass);

            final CSVDecoder decoder = new CSVDecoder(firstPass, MockReference.class);
            try (final CloseableIterator decoded = decoder.decodeLazy()) {
                new CSVEncoder(secondPass, MockReference.class).encode(decoded, true);
            }

            Assert.assertArrayEquals("Encoded md5 is not equal to read then re-encoded data file !", md5, computeDigest(digest, secondPass));

        } finally {
            Files.delete(firstPass);
            Files.delete(secondPass);
        }
    }

    private static byte[] computeDigest(final MessageDigest digest, final Path in) throws IOException {
        final byte[] buf = new byte[8192];
        int read = 0;
        try (final InputStream stream = Files.newInputStream(in)) {
            while ((read = stream.read(buf)) >= 0) {
                digest.update(buf, 0, read);
            }
        }

        return digest.digest();
    }

    /**
     * An iterator creating randomly filled objects as browsed.
     */
    private static class RefCreator implements Iterator<MockReference> {

        private final int total;
        private final AtomicInteger count = new AtomicInteger();

        private MockReference next;

        private final Random random;

        public RefCreator(final int count) {
            ArgumentChecks.ensureStrictlyPositive("Number of references to create", count);
            this.total = count;

            random = new Random();
        }

        @Override
        public synchronized boolean hasNext() {
            if (next == null && count.getAndIncrement() >= total) {
                return false;
            } else if (next == null) {
                next = createReference();
            }

            return true;
        }

        @Override
        public synchronized MockReference next() {
            if (hasNext()) {
                try {
                    return next;
                } finally {
                    next = null;
                }
            } else {
                throw new IllegalStateException("No more element available !");
            }
        }

        private MockReference createReference() {
            MockReference result = new MockReference();

            // Insert a random character sequence, or let a null value.
            if (random.nextBoolean()) {
                final StringBuilder b = new StringBuilder();
                final byte[] bytes = new byte[random.nextInt(128)];
                result.setFirst(new String(bytes, StandardCharsets.UTF_8));
            }

            if (random.nextBoolean()) {
                result.setSecond(ZonedDateTime.now());
            }

            result.setThird(random.nextDouble() * 1e6);

            result.setFourth(random.nextBoolean());

            result.setFifth(random.nextBoolean()? Float.NaN : random.nextFloat());

            return result;
        }
    }
}
