package com.redhat.ceylon.compiler.loader;

import java.util.Map;

import com.redhat.ceylon.compiler.js.CompilerErrorException;
import com.redhat.ceylon.compiler.typechecker.model.Module;

public class JsonModule extends Module {

    private Map<String,Object> model;

    public void setModel(Map<String, Object> value) {
        if (model != null) {
            throw new IllegalStateException("JsonModule should only receive model once");
        }
        model = value;
    }
    public Map<String, Object> getModel() {
        return model;
    }

    void loadDeclarations() {
        if (model != null) {
            for (com.redhat.ceylon.compiler.typechecker.model.Package pkg : getPackages()) {
                if (pkg instanceof JsonPackage) {
                    ((JsonPackage) pkg).loadDeclarations();
                }
            }
        }
    }

    @SuppressWarnings("unchecked")
    public Map<String,Object> getModelForPackage(String name) {
        return model == null ? null : (Map<String,Object>)model.get(name);
    }

    @Override
    public com.redhat.ceylon.compiler.typechecker.model.Package getPackage(String name) {
        if ("default".equals(name)) {
            name = "";
        }
        final com.redhat.ceylon.compiler.typechecker.model.Package p = super.getPackage(name);
        if (p == null) {
            throw new CompilerErrorException("Package " + name + " not available");
        }
        return p;
    }

}

@@ -58,16 +58,42 @@
 til.Map;
+%0Aimport java.util.Objects;
 %0A%0Aimport
@@ -388,84 +388,500 @@
     
-throw new IllegalStateException(%22JsonModule should only receive model once%22)
+final String modName = (String)model.get(%22$mod-name%22);%0A            final String modVers = (String)model.get(%22$mod-version%22);%0A            if (!(Objects.equals(modName, value.get(%22$mod-name%22))%0A                    && Objects.equals(modVers, value.get(%22$mod-version%22)))) %7B%0A                throw new IllegalStateException(%22JsonModule %22 + modName+%22/%22+modVers%0A                        + %22 receives new module %22 + value.get(%22$mod-name%22)+%22/%22+value.get(%22$mod-version%22));%0A            %7D%0A            return
 ;%0A  

throw only when setting a new module different from existing one