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

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Iterator;
import java.util.Set;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.apache.sis.util.Numbers;
import org.apache.sis.util.ObjectConverter;
import org.apache.sis.util.ObjectConverters;

/**
 * Encode data holded by POJO of a specific type into a CSV file.
 *
 * @author Alexis Manin (Geomatys)
 */
public class CSVEncoder<T> extends CSVMapper<T> {

    static final Pattern DOUBLE_QUOTE = Pattern.compile("\"");
    static final String DOUBLE_QUOTE_REPLACEMENT = "\"\"";

    private final Function[] converters;

    /**
     * Create a new encoder whose aim is to write pojo properties in the given file.
     * @param output The file to write. If not exists, we'll try to create it.
     * However, its parent directory MUST exist already.
     * @param beanClass The class defining POJO object we'll have to extract data from.
     * @throws IOException If we cannot create the file, or it already exists and we cannot analyze its header.
     * @throws IntrospectionException If we cannot analyze input pojo type.
     */
    public CSVEncoder(Path output, Class<T> beanClass) throws IOException, IntrospectionException {
        this(output, beanClass, null);
    }

    /**
     * Create a new encoder whose aim is to write pojo preoprties in the given file.
     * @param output The file to write. If not exists, we'll try to create it.
     * However, its parent directory MUST exist already.
     * @param beanClass The class defining POJO object we'll have to extract data from.
     * to read.
     * @param fileEncoding Encoding to use for writing.
     * @throws IOException If we cannot create the file, or it already exists and we cannot analyze its header.
     * @throws IntrospectionException If we cannot analyze input pojo type.
     */
    public CSVEncoder(Path output, Class<T> beanClass, Charset fileEncoding) throws IOException, IntrospectionException {
        this(output, beanClass, fileEncoding, null);
    }

    public CSVEncoder(Path output, Class<T> beanClass, Charset fileEncoding, Set<String> ignorableProperties) throws IOException, IntrospectionException {
        this(output, beanClass, null, fileEncoding, ignorableProperties);
    }

    public CSVEncoder(final Path output, final Class<T> beanClass, final Character separator, final Charset fileEncoding, final Set<String> ignorableProperties) throws IOException, IntrospectionException {
        super(output, beanClass, separator, fileEncoding, ignorableProperties);

        /* Prepare data conversion. For each property present in input bean type,
         * we ensure that a read method is available. Then, we analyze its return
         * type. We try to find an appropriate converter to get a string
         * representation writable in CSV file.
         */
        final PropertyDescriptor[] pDescriptors = beanInfo.getPropertyDescriptors();
        converters = new Function[pDescriptors.length];
        for (int i = 0 ; i < pDescriptors.length; i++) {
            final PropertyDescriptor p = pDescriptors[i];
            final Method readMethod = p.getReadMethod();
            if (readMethod == null)
                throw new IllegalArgumentException(
                        new StringBuilder("Property ")
                                .append(p.getName())
                                .append(" from class ")
                                .append(beanClass.getCanonicalName())
                                .append("is not readable.")
                                .toString());

            readMethod.setAccessible(true);
            final Class returnType = readMethod.getReturnType();
            Function conv = createPropertyConverter(returnType);
            final Function getter = in -> {
                try {
                    return readMethod.invoke(in);
                } catch (IllegalAccessException|InvocationTargetException e) {
                    throw new RhomeoRuntimeException(e);
                }
            };

            if (conv ==null) {
                converters[i] = getter;
            } else {
                converters[i] = getter.andThen(conv);
            }
        }
    }

    /**
     * Create string representation of a given object.
     * @param data the object to encode in CSV.
     * @return A line to put in CSV file.
     */
    private String encode(T data) {
        final StringBuilder builder = new StringBuilder();
        Object value = getPropertyValue(data, 0);
        if (value != null) {
            builder.append(trimAndEscape(value));
        }

        for (int i = 1; i < converters.length; i++) {
            builder.append(this.separator);
            value = getPropertyValue(data, i);
            if (value != null) {
                builder.append(trimAndEscape(value));
            }
        }

        return builder.toString();
    }

    /**
     * Extract value of a property from input pojo, the one located on the given
     * column index in the file.
     * @param data The pojo to extract value from.
     * @param colIndex Index of the property to extract in target file columns.
     * @return The extracted value or a default one if input object property is
     * null or does not exists. Can return a null value.
     */
    private Object getPropertyValue(final T data, final int colIndex) {
        Object value;
        final int pIndex = propertyOrder[colIndex];
        if (pIndex < 0)
            value = null;
        else
            value = converters[pIndex].apply(data);
        return value;
    }

    /**
     * Write data pointed by given iterator.
     * @param data An iterator which provides objects to write.
     * @param replaceExisting If true, data previously written will be erased.
     * Otherwise, we'll append data at the end of the file.
     * @throws IOException If an error occurs while writing data.
     */
    public synchronized void encode(Iterator<T> data, final boolean replaceExisting) throws IOException {
        if (!Files.exists(target)) {
            Files.createFile(target);
        }

        /* Check target file header. If we're in append mode, but no header exists,
         * we set a flag to ensure it will be created. If it is here but is not
         * compatible with our data type, we raise an exception.
         */
        boolean emptyHeader = false;
        try (final BufferedReader reader = Files.newBufferedReader(target, charset)) {
            final String firstLine = reader.readLine();
            if (firstLine == null) {
                emptyHeader = true;
            } else if (!replaceExisting) {
                if (isValidHeader(firstLine)) {
                    updatePropertyOrder(firstLine);
                } else {
                    throw new IllegalArgumentException("Given file already exists, but its header is not complient with given data type.");
                }
            }
        }

        try (BufferedWriter writer = Files.newBufferedWriter(target, charset,
                StandardOpenOption.CREATE,
                replaceExisting ? StandardOpenOption.TRUNCATE_EXISTING : StandardOpenOption.APPEND)) {
            if (replaceExisting || emptyHeader) {
                writer.write(buildHeader());
            }
            while (data.hasNext()) {
                writer.newLine();
                writer.write(encode(data.next()));

            }
        }
    }

    /**
     * Write data pointed by given collection.
     * @param data A collection which provides objects to write.
     * @param replaceExisting If true, data previously written will be erased.
     * Otherwise, we'll append data at the end of the file.
     * @throws IOException If an error occurs while writing data.
     */
    public void encode(Iterable<T> data, final boolean replaceExisting) throws IOException {
        final Iterator<T> it = data.iterator();
        try {
            encode(it, replaceExisting);
        } finally {
            if (it instanceof AutoCloseable) {
                try {
                    ((AutoCloseable)it).close();
                } catch (Exception ex) {
                    RhomeoCore.LOGGER.log(Level.WARNING, "Cannot close a resource !", ex);
                }
            }
        }
    }

    /**
     * Search for an appropriate converter between given type and string.
     * @param <I> Type of object to convert.
     * @param inputType Type of object to convert.
     * @return A ready-to-use converter, or null if we don't need any.
     */
    private <I> Function<I, String> createPropertyConverter(final Class<I> inputType) {
        final Function<I, String> result;
        if (inputType.isPrimitive()
                || Number.class.isAssignableFrom(inputType)
                || CharSequence.class.isAssignableFrom(inputType)
                || Boolean.class.isAssignableFrom(inputType)) {
            result = null;

        } else {
            final Class tmpClass = Numbers.primitiveToWrapper(inputType);
            ObjectConverter<? super I, ? extends String> sisConverter = ObjectConverters.find(tmpClass, String.class);
            result = input -> {
                return input == null? null : sisConverter.apply(input);
            };
        }

        return result;
    }

    /**
     * Analyze input string, and modify it if the CSV separator character is
     * found inside. First, we remove blank spaces at start and end of the
     * string. Then, we'll search for provided separator character. If we find
     * it, we escape the string using '"' character. If the string also contains
     * '"' characters, we double them.
     *
     * @param input String to analyze.
     * @return Input string if we don't have to escape it. A new one otherwise.
     */
    private String trimAndEscape(final Object input) {
        String result = input.toString().trim();
        if (result.contains(String.valueOf(separator)) || result.contains(String.valueOf(COMMENT_CHAR))) {
            result = new StringBuilder(result.length() +2)
                    .append('"')
                    .append(DOUBLE_QUOTE.matcher(result).replaceAll(DOUBLE_QUOTE_REPLACEMENT))
                    .append('"')
                    .toString();
        }

        return result;
    }
}
