/*******************************************************************************
 * Copyright (c) 2016 ModelSolv, Inc. and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    ModelSolv, Inc. - initial API and implementation and/or initial documentation
 *******************************************************************************/
package com.reprezen.swagedit.core.json.references;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;

import org.eclipse.core.resources.IFile;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.reprezen.swagedit.core.utils.DocumentUtils;

/**
 * JsonDocumentManager
 */
public class JsonDocumentManager {

    private static final JsonDocumentManager INSTANCE = new JsonDocumentManager();

    public static JsonDocumentManager getInstance() {
        return INSTANCE;
    }

    // for tests
    public JsonDocumentManager() {
    }

    private final ObjectMapper mapper = new ObjectMapper();
    private final ObjectMapper yamlMapper = new ObjectMapper(new YAMLFactory());

    private final Map<URL, JsonNode> documents = Collections.synchronizedMap(new WeakHashMap<URL, JsonNode>());

    /**
     * Returns the JSON representation of the document located at the given URL. If the document is not found or the
     * document is not a valid JSON nor a valid YAML document, this method returns null.
     * 
     * @param url
     *            of the document
     * @return JSON tree
     */
    public JsonNode getDocument(URL url) {
        URL normalized = normalize(url);

        if (documents.containsKey(normalized)) {
            return documents.get(normalized);
        }

        JsonNode document = parse(normalized);
        if (document != null) {
            documents.put(normalized, document);
        }
        return document;
    }

    public JsonNode getDocument(URI uri) {
        try {
            return getDocument(uri.toURL());
        } catch (IllegalArgumentException | MalformedURLException e) {
            return null;
        }
    }

    /**
     * Returns the file located at the given URI if present in the workspace. Returns null otherwise.
     * 
     * @param uri
     *            - workspace file URI
     * @return file
     */
    public IFile getFile(URI uri) {
        return uri != null ? DocumentUtils.getWorkspaceFile(uri) : null;
    }

    private JsonNode parse(URL url) {
        if (url.getFile().endsWith("json")) {
            try {
                return mapper.readTree(url);
            } catch (Exception e) {
                return null;
            }
        } else if (url.getFile().endsWith("yaml") || url.getFile().endsWith("yml")) {
            try {
                return yamlMapper.readTree(url);
            } catch (Exception e) {
                return null;
            }
        } else {
            // cannot decide which format, so we try both parsers
            try {
                return mapper.readTree(url);
            } catch (Exception e) {
                try {
                    return yamlMapper.readTree(url);
                } catch (Exception ee) {
                    return null;
                }
            }
        }
    }

    private URL normalize(URL url) {
        try {
            return new URL(url.getProtocol(), url.getHost(), url.getFile());
        } catch (MalformedURLException e) {
            return url;
        }
    }

}

@@ -609,16 +609,37 @@
 ences;%0A%0A
+import java.io.File;%0A
 import j
@@ -711,16 +711,44 @@
 et.URL;%0A
+import java.nio.file.Paths;%0A
 import j
@@ -1623,24 +1623,135 @@
 sonNode%3E());
+%0A    private final Map%3CURL, Long%3E documentVersions = Collections.synchronizedMap(new WeakHashMap%3CURL, Long%3E());
 %0A%0A    /**%0A  
@@ -2130,16 +2130,231 @@
 ze(url);
+%0A        Long currentTime = getTimestamp(normalized);%0A%0A        Long previousTime = -1L;%0A        if (documentVersions.containsKey(normalized)) %7B%0A             previousTime = documentVersions.get(normalized);%0A        %7D
 %0A%0A      
@@ -2384,32 +2384,63 @@
 sKey(normalized)
+ && previousTime %3E= currentTime
 ) %7B%0A            
@@ -2612,16 +2612,128 @@
 ument);%0A
+            if (currentTime %3E 0) %7B%0A                documentVersions.put(normalized, currentTime);%0A            %7D%0A
         
@@ -2726,32 +2726,33 @@
     %7D%0A        %7D%0A
+%0A
         return d
@@ -3293,32 +3293,277 @@
  : null;%0A    %7D%0A%0A
+    private Long getTimestamp(URL url) %7B%0A        try %7B%0A            File file = Paths.get(url.toURI()).toFile();%0A%0A            return file != null ? file.lastModified() : 0L;%0A        %7D catch (Exception e) %7B%0A            return 0L;%0A        %7D%0A    %7D%0A%0A
     private Json

Allow references to components in non-OAS files, through any path