/* Generated By:JavaCC: Do not edit this line. MMD2OWL.java */
package lv.lumii.tda.kernel.mmdparser;

import java.io.*;
import java.util.*;
import org.apache.commons.io.IOUtils;

public class MMD2OWL implements MMD2OWLConstants {
  public static boolean debug = false;
  private java.io.PrintStream output;

  public static void main(String args[]) throws ParseException {
    InputStream streamCopy;
    String str;
        try
        {
        str = IOUtils.toString(System.in, "UTF-8");
        byte[] b = str.getBytes("UTF-8");
                streamCopy = new ByteArrayInputStream(b);
        }
        catch(Throwable t)
        {
                System.err.println(t.toString());
                return;
        }

    Set<String> dups = new HashSet<String>();
    MMD2OWL p = new MMD2OWL(streamCopy);

    String err = p.checkSyntax(dups);
    if (err!=null)
    {
        System.err.println("Syntax check error: "+err);
        return;
    }

    if (dups.size() >0)
    {
        System.err.println(dups.size()+" duplicates found:");
        for (String s : dups)
                System.err.println("  "+s);
   }

        try
        {
        byte[] b = str.getBytes("UTF-8");
                streamCopy = new ByteArrayInputStream(b);
        }
        catch(Throwable t)
        {
                System.err.println(t.toString());
                return;
        }


    MMD2OWL p2 = new MMD2OWL(streamCopy);
    p2.setDuplicates(dups);
    err = p2.mmd2owl(System.out);
    if (err!=null)
        System.err.println("Error: "+err);
  }

  private Set<String> names = new HashSet<String>();
  private Set<String> duplicateNames = new HashSet<String>();
  private boolean onlyCheckSyntax = true;
  private StringBuffer loadErrors = null;

  private String removeQuotes(String s)
  {
    if ((s.length()>=2) && (s.codePointAt(0)==0x22) && (s.codePointAt(s.length()-1)==0x22))
        return s.substring(1, s.length()-1);
    if ((s.length()>=2) && (s.codePointAt(0)==0x201C) && (s.codePointAt(s.length()-1)==0x201D))
        return s.substring(1, s.length()-1);
    if (s.startsWith("'") && s.endsWith("'"))
        return s.substring(1, s.length()-1);
    else
        return s;
  }

  public void setDuplicates(Set<String> duplicates)
  {
    duplicateNames.addAll(duplicates);
  }

  public String checkSyntax(Set<String> returnedDuplicates)
  {
    onlyCheckSyntax = true;
    names.clear();
    duplicateNames.clear();
    try
    {
        output = null;
        Start();
        returnedDuplicates.addAll(duplicateNames);
        return null;
        } catch (ParseException e1) {
          return e1.toString();
        }
  }
    // returns null if OK, or error description
  public String mmd2owl(java.io.PrintStream _output)
  {
    onlyCheckSyntax = false;
    output = _output;
    loadErrors = new StringBuffer();
    try
    {
        output.println("Prefix(:=<http://tda.lumii.lv/GraphDiagramEngineMetamodel/v1.5#>)");
        output.println("Prefix(xsd:=<http://www.w3.org/2001/XMLSchema#>)");
                output.println("Ontology( <http://tda.lumii.lv/GraphDiagramEngineMetamodel/v1.5>");
        Start();
                output.println(")"); // end of ontology
        if (loadErrors.length()==0) {
          loadErrors = null;
          output = null;
          return null;
                }
                else {
                  output = null;
                  String s = loadErrors.toString();
                  loadErrors.delete(0, loadErrors.length());
                  loadErrors = null;
                  return s;
                }
        } catch (ParseException e1) {
          output = null;
          String s = loadErrors.toString();
          loadErrors.delete(0, loadErrors.length());
          loadErrors = null;
          return e1.toString();//s;
        }
  }

  private String makeName(String s)
  {
    s = removeQuotes(s.replaceAll("\u005c\u005cs+",""));
    int i=s.indexOf(":");
    while (i >= 0)
    {
      s = s.substring(0, i)+s.substring(i+1);
      i=s.indexOf(":");
    }
    return s;
  }

  final public void Start() throws ParseException {
    jj_consume_token(6);
    label_1:
    while (true) {
      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
      case 9:
      case 10:
      case 13:
      case 15:
      case 16:
        ;
        break;
      default:
        jj_la1[0] = jj_gen;
        break label_1;
      }
      MetamodelOperation();
      jj_consume_token(7);
    }
    jj_consume_token(8);
    jj_consume_token(0);
  }

  final public void MetamodelOperation() throws ParseException {
    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
    case 9:
      Class();
      break;
    case 10:
      Attr();
      break;
    case 13:
      Rel();
      break;
    case 15:
    case 16:
      Assoc();
      break;
    default:
      jj_la1[1] = jj_gen;
      jj_consume_token(-1);
      throw new ParseException();
    }
  }

  final public void Class() throws ParseException {
    jj_consume_token(9);
    jj_consume_token(NAME);
          if (!onlyCheckSyntax)
          {
                  if (MMDParser.debug)
                    System.out.println(" >>adding class `" + token.image + "'...");

                  output.println("Declaration(Class(:"+makeName(token.image)+"))"); // removing spaces...
          }
          else
          {
                        String name = makeName(token.image);
                        if (names.contains(name))
                                duplicateNames.add(name);
                        else
                                names.add(name);
          }
  }

  final public void Attr() throws ParseException {
  String className;
  String attrName;
  String attrType;
    jj_consume_token(10);
    jj_consume_token(NAME);
                className=makeName(token.image);
    jj_consume_token(11);
    jj_consume_token(NAME);
                attrName=makeName(token.image);
    jj_consume_token(12);
    jj_consume_token(NAME);
                attrType=makeName(token.image).toLowerCase();
          if (!onlyCheckSyntax)
          {
                  if (duplicateNames.contains(attrName))
                attrName += "Of"+className;

                  if (MMDParser.debug)
                    System.out.println(">>adding "+attrType+" attr "+attrName+" of "+className+"...");

                    // TODO: adjust attrName

                  output.println("Declaration(DataProperty(:"+attrName+"))");
                  output.println("DataPropertyDomain(:"+attrName+" :"+className+")");
                  if (attrType.startsWith("int"))
                    output.println("DataPropertyRange( :"+attrName+" xsd:integer )");
                  else
                  if (attrType.equals("real") || attrType.equals("float"))
                    output.println("DataPropertyRange( :"+attrName+" xsd:decimal )");
                  else
                    output.println("DataPropertyRange( :"+attrName+" xsd:string )");

          }
          else
          {
                        if (names.contains(attrName))
                                duplicateNames.add(attrName);
                        else
                                names.add(attrName);
          }
  }

  final public void Rel() throws ParseException {
        String subClassName;
        String superClassName;
    jj_consume_token(13);
    jj_consume_token(NAME);
                subClassName=makeName(token.image);
    jj_consume_token(11);
    jj_consume_token(14);
    jj_consume_token(11);
    jj_consume_token(NAME);
                superClassName=makeName(token.image);
          if (!onlyCheckSyntax)
          {
        if (MMDParser.debug)
                  System.out.println(">>generalization "+subClassName+"->"+superClassName+"...");
                  output.println("SubClassOf(:"+subClassName+" :"+superClassName+")");
          }
  }

  final public void Assoc() throws ParseException {
        boolean isComposition;
        String sourceClass;
        String sourceRole;
        String sourceCardinality;
        String targetClass;
        String targetRole;
        String targetCardinality;
        boolean sourceOrdered;
        boolean targetOrdered;
    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
    case 15:
      jj_consume_token(15);
                   isComposition=false;
      break;
    case 16:
      jj_consume_token(16);
                   isComposition=true;
      break;
    default:
      jj_la1[2] = jj_gen;
      jj_consume_token(-1);
      throw new ParseException();
    }
    jj_consume_token(NAME);
                sourceClass=makeName(token.image);
    jj_consume_token(11);
    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
    case 17:
      jj_consume_token(17);
      break;
    default:
      jj_la1[3] = jj_gen;
      ;
    }
                       sourceOrdered = token.image.equals("{ordered}");
    jj_consume_token(18);
    Cardinality();
                       sourceCardinality=token.image;
    jj_consume_token(19);
    jj_consume_token(NAME);
                sourceRole=makeName(token.image);
    jj_consume_token(20);
    jj_consume_token(NAME);
                targetRole=makeName(token.image);
    jj_consume_token(18);
    Cardinality();
                       targetCardinality=token.image;
    jj_consume_token(19);
    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
    case 17:
      jj_consume_token(17);
      break;
    default:
      jj_la1[4] = jj_gen;
      ;
    }
                       targetOrdered = token.image.equals("{ordered}");
    jj_consume_token(11);
    jj_consume_token(NAME);
                targetClass=makeName(token.image);
          if (!onlyCheckSyntax)
          {
                if (duplicateNames.contains(sourceRole))
                        sourceRole += "Of"+targetClass;
                if (duplicateNames.contains(targetRole))
                        targetRole += "Of"+sourceClass;

        if (MMDParser.debug) {
              if (isComposition)
                System.out.print(">>compos ");
              else
                System.out.print(">>assoc ");
              System.out.println(sourceClass+" "+sourceCardinality+" "+sourceRole+" "+sourceOrdered+" <-> "+
                                         targetClass+" "+targetCardinality+" "+targetRole+" "+targetOrdered+"...");
        }

                String msg = "Could not create ";
                if (isComposition)
                  msg += "composition ";
                else
                  msg += "association ";
            msg += "between "+sourceClass+"["+sourceCardinality+"]("+sourceRole+") and "+
                                     targetClass+"["+targetCardinality+"]("+targetRole+").";

                output.println("Declaration(ObjectProperty(:"+sourceRole+"))");
                output.println("Declaration(ObjectProperty(:"+targetRole+"))");

                output.println("InverseObjectProperties(:"+sourceRole+" :"+targetRole+")");

                output.println("ObjectPropertyDomain(:"+targetRole+" :"+sourceClass+")");
                output.println("ObjectPropertyRange(:"+targetRole+" :"+targetClass+")");
                output.println("ObjectPropertyDomain(:"+sourceRole+" :"+targetClass+")");
                output.println("ObjectPropertyRange(:"+sourceRole+" :"+sourceClass+")");
          }
          else
          {
                if (names.contains(sourceRole))
                        duplicateNames.add(sourceRole);
                else
                        names.add(sourceRole);
                if (names.contains(targetRole))
                        duplicateNames.add(targetRole);
                else
                        names.add(targetRole);
          }
  }

  final public void Cardinality() throws ParseException {
    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
    case 21:
      jj_consume_token(21);
      break;
    case 22:
      jj_consume_token(22);
      break;
    case 23:
      jj_consume_token(23);
      break;
    case 24:
      jj_consume_token(24);
      break;
    case 25:
      jj_consume_token(25);
      break;
    case 26:
      jj_consume_token(26);
      break;
    default:
      jj_la1[5] = jj_gen;
      jj_consume_token(-1);
      throw new ParseException();
    }
  }

  /** Generated Token Manager. */
  public MMD2OWLTokenManager token_source;
  SimpleCharStream jj_input_stream;
  /** Current token. */
  public Token token;
  /** Next token. */
  public Token jj_nt;
  private int jj_ntk;
  private int jj_gen;
  final private int[] jj_la1 = new int[6];
  static private int[] jj_la1_0;
  static {
      jj_la1_init_0();
   }
   private static void jj_la1_init_0() {
      jj_la1_0 = new int[] {0x1a600,0x1a600,0x18000,0x20000,0x20000,0x7e00000,};
   }

  /** Constructor with InputStream. */
  public MMD2OWL(java.io.InputStream stream) {
     this(stream, null);
  }
  /** Constructor with InputStream and supplied encoding */
  public MMD2OWL(java.io.InputStream stream, String encoding) {
    try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
    token_source = new MMD2OWLTokenManager(jj_input_stream);
    token = new Token();
    jj_ntk = -1;
    jj_gen = 0;
    for (int i = 0; i < 6; i++) jj_la1[i] = -1;
  }

  /** Reinitialise. */
  public void ReInit(java.io.InputStream stream) {
     ReInit(stream, null);
  }
  /** Reinitialise. */
  public void ReInit(java.io.InputStream stream, String encoding) {
    try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
    token_source.ReInit(jj_input_stream);
    token = new Token();
    jj_ntk = -1;
    jj_gen = 0;
    for (int i = 0; i < 6; i++) jj_la1[i] = -1;
  }

  /** Constructor. */
  public MMD2OWL(java.io.Reader stream) {
    jj_input_stream = new SimpleCharStream(stream, 1, 1);
    token_source = new MMD2OWLTokenManager(jj_input_stream);
    token = new Token();
    jj_ntk = -1;
    jj_gen = 0;
    for (int i = 0; i < 6; i++) jj_la1[i] = -1;
  }

  /** Reinitialise. */
  public void ReInit(java.io.Reader stream) {
    jj_input_stream.ReInit(stream, 1, 1);
    token_source.ReInit(jj_input_stream);
    token = new Token();
    jj_ntk = -1;
    jj_gen = 0;
    for (int i = 0; i < 6; i++) jj_la1[i] = -1;
  }

  /** Constructor with generated Token Manager. */
  public MMD2OWL(MMD2OWLTokenManager tm) {
    token_source = tm;
    token = new Token();
    jj_ntk = -1;
    jj_gen = 0;
    for (int i = 0; i < 6; i++) jj_la1[i] = -1;
  }

  /** Reinitialise. */
  public void ReInit(MMD2OWLTokenManager tm) {
    token_source = tm;
    token = new Token();
    jj_ntk = -1;
    jj_gen = 0;
    for (int i = 0; i < 6; i++) jj_la1[i] = -1;
  }

  private Token jj_consume_token(int kind) throws ParseException {
    Token oldToken;
    if ((oldToken = token).next != null) token = token.next;
    else token = token.next = token_source.getNextToken();
    jj_ntk = -1;
    if (token.kind == kind) {
      jj_gen++;
      return token;
    }
    token = oldToken;
    jj_kind = kind;
    throw generateParseException();
  }


/** Get the next Token. */
  final public Token getNextToken() {
    if (token.next != null) token = token.next;
    else token = token.next = token_source.getNextToken();
    jj_ntk = -1;
    jj_gen++;
    return token;
  }

/** Get the specific Token. */
  final public Token getToken(int index) {
    Token t = token;
    for (int i = 0; i < index; i++) {
      if (t.next != null) t = t.next;
      else t = t.next = token_source.getNextToken();
    }
    return t;
  }

  private int jj_ntk() {
    if ((jj_nt=token.next) == null)
      return (jj_ntk = (token.next=token_source.getNextToken()).kind);
    else
      return (jj_ntk = jj_nt.kind);
  }

  private java.util.List<int[]> jj_expentries = new java.util.ArrayList<int[]>();
  private int[] jj_expentry;
  private int jj_kind = -1;

  /** Generate ParseException. */
  public ParseException generateParseException() {
    jj_expentries.clear();
    boolean[] la1tokens = new boolean[28];
    if (jj_kind >= 0) {
      la1tokens[jj_kind] = true;
      jj_kind = -1;
    }
    for (int i = 0; i < 6; i++) {
      if (jj_la1[i] == jj_gen) {
        for (int j = 0; j < 32; j++) {
          if ((jj_la1_0[i] & (1<<j)) != 0) {
            la1tokens[j] = true;
          }
        }
      }
    }
    for (int i = 0; i < 28; i++) {
      if (la1tokens[i]) {
        jj_expentry = new int[1];
        jj_expentry[0] = i;
        jj_expentries.add(jj_expentry);
      }
    }
    int[][] exptokseq = new int[jj_expentries.size()][];
    for (int i = 0; i < jj_expentries.size(); i++) {
      exptokseq[i] = jj_expentries.get(i);
    }
    return new ParseException(token, exptokseq, tokenImage);
  }

  /** Enable tracing. */
  final public void enable_tracing() {
  }

  /** Disable tracing. */
  final public void disable_tracing() {
  }

}
