package mildo.wiwo.data;

import mildo.wiwo.persistence.PersistHelper;

import org.apache.log4j.Logger;

import and.wo.eof.SortOrderingKeyHelper;

import com.webobjects.eocontrol.EOEditingContext;
import com.webobjects.eocontrol.EOQualifier;
import com.webobjects.eocontrol.EOSortOrdering;
import com.webobjects.foundation.NSArray;
import com.webobjects.foundation.NSTimestamp;

public class WiwoPage 
	extends _WiwoPage 
{
	
	private static Logger log = Logger.getLogger(WiwoPage.class);
	
	/**
	 * Creates new version of page.
	 * @param aCtx
	 * @param anUser
	 * @param aName
	 * @param aMarkupText
	 * @param aPreviousVerion
	 * @return
	 */
	public static WiwoPage createPage(EOEditingContext aCtx, WiwoUser anUser, String aName, String aMarkupText, WiwoPage aPreviousVerion) {
		int theVerTag = 1;
		if (aPreviousVerion != null) {
			int thePrevVerTag = aPreviousVerion.versionTag().intValue();
			theVerTag = thePrevVerTag + 1;
		} 
		WiwoPage ret = createWiwoPage(aCtx, aName, new NSTimestamp(), new Integer(theVerTag), aMarkupText, anUser);
		if (aPreviousVerion != null) {
			ret.setPreviousVersionRelationship(aPreviousVerion);
		}
		return ret;
	}
	
	/**
	 * Creates entirely new wiwo page.
	 * @param aCtx
	 * @param anUser
	 * @param aName
	 * @param aMarkupText
	 * @return
	 */
	public static WiwoPage createPage(EOEditingContext aCtx, WiwoUser anUser, String aName, String aMarkupText) {
		return createPage(aCtx, anUser, aName, aMarkupText, null);
	}
	
	public static boolean canCreateNewWiwoPage(EOEditingContext aCtx, String aName) {
		return fetchWiwoPages(aCtx, PersistHelper.makeEqQualifier("name", aName), null).isEmpty();
	}
	
	/**
	 * Fetches newest version of WiwoPage with given name.
	 * @param aCtx
	 * @param aPageName
	 * @return
	 */
	public static WiwoPage fetchPageWithName(EOEditingContext aCtx, String aPageName) {
		WiwoPage ret = null;
		EOQualifier theQual = PersistHelper.makeEqQualifier("name", aPageName);
		NSArray thePages = WiwoPage.fetchWiwoPages(aCtx, theQual, SortOrderingKeyHelper.sortOrderingsFor("versionTag"));
		if (!thePages.isEmpty()) {
			ret = (WiwoPage) thePages.lastObject();
		}
		return ret;
	}
	
}

