package org.opengroupware.jope.eoaccess.tests;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import java.net.URL;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.opengroupware.jope.eoaccess.EOEntity;
import org.opengroupware.jope.eoaccess.EOModel;
import org.opengroupware.jope.eoaccess.EOModelLoader;
import org.opengroupware.jope.eoaccess.EORelationship;
import org.opengroupware.jope.eocontrol.EOFetchSpecification;

public class ModelLoading {
  
  protected EOModelLoader loader;

  @Before
  public void setUp() {
    this.loader = new EOModelLoader(); 
  }

  @After
  public void tearDown() {
    this.loader = null;
  }
  
  @Test
  public void testModelWithDerivedNames() {
    EOModel model = this.loadModel("ModelWithDerivedNames");
    assertNotNull("could not load model", model);
    assertNull("error in loading model", this.loader.lastException());
    
    EOEntity contact = model.entityNamed("Contact");
    EOEntity notes   = model.entityNamed("notes");
    assertNotNull("missing Contact entity", contact);
    assertNotNull("missing notes entity",   notes);
    
    assertTrue("Contact is not a pattern", contact.isPatternEntity());
    assertTrue("notes is not a pattern",   notes.isPatternEntity());
    
    /* fetch specs */

    EOFetchSpecification fs = contact.fetchSpecificationNamed("count");
    assertNotNull("missing count fetch-spec of Contact", fs);
    assertNotNull(fs.hints());
    assertNotNull(fs.hints().get("EOCustomQueryExpressionHintKey"));
    
    fs = contact.fetchSpecificationNamed("allDucks");
    assertNotNull("missing allDucks fetch-spec of Contact", fs);
    //System.err.println("D: " + fs);
    
    /* relationships */
    
    EORelationship toNotes = contact.relationshipNamed("toNotes");
    assertNotNull("missing toNotes relship in Contact entity", toNotes);

    EORelationship toContact = notes.relationshipNamed("toContact");
    assertNotNull("missing toContact relship in notes entity", toContact);
  }

  @Test
  public void testModelWithAttrNamePatterns() {
    EOModel model = this.loadModel("ModelWithAttrNamePatterns");
    assertNotNull("could not load model", model);
    assertNull("error in loading model", this.loader.lastException());

    EOEntity contact = model.entityNamed("Contact");
    assertNotNull("missing Contact entity", contact);
    assertNotNull("missing jopetest_notes entity",
                  model.entityNamed("jopetest_notes"));
  }
  
  /* support */
  
  protected EOModel loadModel(String _model) {
    URL url = ModelLoading.class.getResource(_model + ".xml");
    return this.loader.loadModelFromURL(url);
  }
}
