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

import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.logging.Level;
import javax.annotation.PreDestroy;
import org.apache.sis.util.NullArgumentException;
import org.geotoolkit.nio.IOUtilities;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

/**
 *
 * @author Alexis Manin (Geomatys)
 */
@Component
public class DocManager {

    protected final Path tmpDir;

    protected DocManager() {
        Path tmp = null;
        try {
            // Init folder to put docs into.
            tmp = Files.createTempDirectory("rhomeo_docs");
        } catch (IOException ex) {
            Rhomeo.LOGGER.log(Level.WARNING, "Impossible to prepare documentation management.", ex);
        }

        tmpDir = tmp;
    }

    public void openDocument(final URL resource) {
        try {
            if (isHref(resource)) {
                Rhomeo.browse(resource);
            }
            final Path p = getPath(resource);
            if (p != null)
                Rhomeo.openFile(p.toFile());
        } catch (Exception e) {
            Rhomeo.LOGGER.log(Level.WARNING, "Cannot open given resource : ".concat(String.valueOf(resource)), e);
        }
    }

    private Path getPath(URL resource) throws URISyntaxException, IOException {
        if (resource == null)
            throw new NullArgumentException("Given resource is null !");
        if ("file".equals(resource.getProtocol()))
            return Paths.get(resource.toURI());
        String md5 = DigestUtils.md5DigestAsHex(resource.toExternalForm().getBytes());
        
        // HACK for win systems which are too dumb to open files without extension
        final String extension = IOUtilities.extension(resource);
        final Path target;
        if (extension != null && !extension.isEmpty())
            target = tmpDir.resolve(md5 + "." + extension);
        else
            target = tmpDir.resolve(md5);

        if (!Files.exists(target)) {
            try (final InputStream source = resource.openStream()) {
                Files.copy(source, target);
            }
        }

        return target;
    }

    @PreDestroy
    private void clear() throws IOException {
        if (tmpDir != null)
            IOUtilities.deleteRecursively(tmpDir);
    }

    private boolean isHref(URL resource) {
        return resource != null && resource.getProtocol().startsWith("http");
    }
}
