/**
 * Copyright © 2010-2014 Nokia
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jsonschema2pojo;

import static org.apache.commons.lang3.StringUtils.*;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.databind.JsonNode;

public class SchemaStore {

    protected Map<URI, Schema> schemas = new HashMap<URI, Schema>();

    protected FragmentResolver fragmentResolver = new FragmentResolver();
    protected ContentResolver contentResolver = new ContentResolver();

    /**
     * Create or look up a new schema which has the given ID and read the
     * contents of the given ID as a URL. If a schema with the given ID is
     * already known, then a reference to the original schema will be returned.
     * 
     * @param id
     *            the id of the schema being created
     * @return a schema object containing the contents of the given path
     */
    public synchronized Schema create(URI id) {

        if (!schemas.containsKey(id)) {

            JsonNode content = contentResolver.resolve(removeFragment(id));

            if (id.toString().contains("#")) {
                JsonNode childContent = fragmentResolver.resolve(content, '#' + substringAfter(id.toString(), "#"));
                schemas.put(id, new Schema(id, childContent, content));
            } else {
                schemas.put(id, new Schema(id, content, content));
            }
        }

        return schemas.get(id);
    }

    protected URI removeFragment(URI id) {
        return URI.create(substringBefore(id.toString(), "#"));
    }

    /**
     * Create or look up a new schema using the given schema as a parent and the
     * path as a relative reference. If a schema with the given parent and
     * relative path is already known, then a reference to the original schema
     * will be returned.
     * 
     * @param parent
     *            the schema which is the parent of the schema to be created.
     * @param path
     *            the relative path of this schema (will be used to create a
     *            complete URI by resolving this path against the parent
     *            schema's id)
     * @return a schema object containing the contents of the given path
     */
    @SuppressWarnings("PMD.UselessParentheses")
    public Schema create(Schema parent, String path) {

        if (path.equals("#")) {
            return parent;
        }
        
        path = stripEnd(path, "#?&/");

        URI id = (parent == null || parent.getId() == null) ? URI.create(path) : parent.getId().resolve(path);

        if (selfReferenceWithoutParentFile(parent, path)) {
            schemas.put(id, new Schema(id, fragmentResolver.resolve(parent.getParentContent(), path), parent.getParentContent()));
            return schemas.get(id);
        }
        
        return create(id);

    }

    protected boolean selfReferenceWithoutParentFile(Schema parent, String path) {
        return parent != null && (parent.getId() == null || parent.getId().toString().startsWith("#/")) && path.startsWith("#/");
    }

    public synchronized void clearCache() {
        schemas.clear();
    }

}

@@ -698,16 +698,52 @@
 et.URI;%0A
+import java.net.URISyntaxException;%0A
 import j
@@ -1770,41 +1770,23 @@
 ' + 
-substringAfter(id.toString(), %22#%22
+id.getFragment(
 ));%0A
@@ -2895,16 +2895,17 @@
     if (
+!
 path.equ
@@ -2928,29 +2928,187 @@
         
-return parent
+// if path is an empty string then resolving it below results in jumping up a level. e.g. %22/path/to/file.json%22 becomes %22/path/to%22%0A            path = stripEnd(path, %22#?&/%22)
 ;%0A      
@@ -3107,32 +3107,33 @@
 ;%0A        %7D%0A
+%0A
         
 %0A        pat
@@ -3124,32 +3124,205 @@
     
-%0A        path = stripEnd
+// encode the fragment for any funny characters%0A        if (path.contains(%22#%22)) %7B%0A            String pathExcludingFragment = substringBefore(path, %22#%22);%0A            String fragment = substringAfter
 (pat
@@ -3330,126 +3330,785 @@
 , %22#
-?&/
 %22);%0A
-%0A        URI id = (parent == null %7C%7C parent.getId() == null) ? URI.create(path) : parent.getId().resolve(path);
+            URI fragmentURI;%0A            try %7B%0A                fragmentURI = new URI(null, null, fragment);%0A            %7D catch (URISyntaxException e) %7B%0A                throw new IllegalArgumentException(%22Invalid fragment: %22 + fragment + %22 in path: %22 + path);%0A            %7D%0A            path = pathExcludingFragment + %22#%22 + fragmentURI.getRawFragment();%0A        %7D%0A%0A        URI id = (parent == null %7C%7C parent.getId() == null) ? URI.create(path) : parent.getId().resolve(path);%0A%0A        String stringId = id.toString();%0A        if (stringId.endsWith(%22#%22)) %7B%0A            try %7B%0A                id = new URI(stripEnd(stringId, %22#%22));%0A            %7D catch (URISyntaxException e) %7B%0A                throw new IllegalArgumentException(%22Bad path: %22 + stringId);%0A            %7D%0A        %7D
 %0A%0A  
@@ -4342,24 +4342,16 @@
       %7D%0A
-        
 %0A       

Fix to schema store to deal with embedded refs