/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package foam.lib.json;

import foam.lib.parse.*;
import foam.core.ClassInfo;

public class PropertyReferenceParser extends ProxyParser {
  public PropertyReferenceParser() {
      super(new Seq0(new Whitespace(),
                      new Literal("{"),
                      new Whitespace(),
                      new KeyParser("class"),
                      new Whitespace(),
                      new Literal(":"),
                      new Whitespace(),
                      new Literal("\"__Property__\""),
                      new Whitespace(),
                      new Literal(","),
                      new Whitespace(),
                      new KeyParser("forClass_"),
                      new Whitespace(),
                      new Literal(":"),
                      new Whitespace(),
                      new Parser() {
                          private Parser delegate = new StringParser();
                          public PStream parse(PStream ps, ParserContext x) {
                            ps = ps.apply(delegate, x);
                            if ( ps != null ) {
                              x.set("forClass_", ps.value());
                            }
                            return ps;
                          }
                        },
                      new Whitespace(),
                      new Literal("}")));
  }
                   
  public PStream parse(PStream ps, ParserContext x) {
    ps = super.parse(ps, x);

    if ( ps != null ) {
      String forClass = (String)x.get("forClass_");
      String classId = forClass.substring(0, forClass.lastIndexOf("."));
      String propName = forClass.substring(forClass.lastIndexOf(".") + 1);

      Class cls;
      try {
        cls = Class.forName(classId);
      } catch(ClassNotFoundException e) {
        throw new RuntimeException(e);
      }

      // TODO(adamvy): Use the context to resolve the class rather than reflection
      // TODO(adamvy): Better handle errors.

      ClassInfo info;
      try {
        info = (ClassInfo)cls.getMethod("getOwnClassInfo").invoke(null);
      } catch(Exception e) {
        throw new RuntimeException(e);
      }

      return ps.setValue(info.getAxiomByName(propName));
    }

    return ps;
  }
}
@@ -1488,28 +1488,9 @@
   %7D%0A
-                   
 %0A
+
   pu
@@ -1666,16 +1666,17 @@
 classId 
+ 
 = forCla
@@ -2141,16 +2141,17 @@
 assInfo)
+ 
 cls.getM
@@ -2276,27 +2276,23 @@
     
-return ps.setValue(
+Object axiom = 
 info
@@ -2316,16 +2316,174 @@
 ropName)
+;%0A%0A      if ( axiom == null ) %7B%0A        System.err.println(%22Unknown Property Reference: %22 + classId + %22.%22 + propName);%0A      %7D%0A%0A      return ps.setValue(axiom
 );%0A    %7D
@@ -2503,9 +2503,10 @@
 ps;%0A  %7D%0A
-
 %7D
+%0A

Add new error message for unknown Property reference.