package siprp.database.cayenne.objects;

import java.text.DateFormat;
import java.util.Locale;

import org.apache.cayenne.CayenneDataObject;
import org.apache.cayenne.PersistenceState;

import siprp.database.cayenne.providers.MainDAO;

import com.evolute.utils.strings.UnicodeChecker;

public class BaseObject extends CayenneDataObject
{

	static {
		UnicodeChecker.setUseDoubleSlash( true );
	}
	
	private static final long serialVersionUID = 1L;
	
	protected static MainDAO dao = new MainDAO();
	
	protected static final DateFormat sdf = DateFormat.getDateInstance( DateFormat.SHORT, new Locale( "pt", "PT" ) );

	protected static final String isNewMessage = " ";
	
	public boolean isTransient()
	{
		return getPersistenceState() == PersistenceState.TRANSIENT;
	}
	
	public boolean isNew()
	{
		return getPersistenceState() == PersistenceState.NEW;
	}
	
	public boolean isCommited()
	{
		return getPersistenceState() == PersistenceState.COMMITTED;
	}
	
	public boolean isModified()
	{
		return getPersistenceState() == PersistenceState.MODIFIED;
	}
	
	public void commit()
	{
		dao.commit();
	}
	
	public void rollback()
	{
		dao.rollback();
	}
	
	public void save() throws Exception
	{
		if( isTransient() )
		{
			dao.getContext().registerNewObject( this );
		}
		commit();
	}
	
	public void delete() throws Exception
	{
		dao.getContext().deleteObject( this );
		commit();
	}
	
	protected String parseToUnicode( String string )
	{
		String result = string == null ? null : UnicodeChecker.parseToUnicode( string );
		return result == null ? null : result.replaceAll( "\\\\\\\\", "\\\\" );
	}
	
	protected String parseFromUnicode( String string )
	{
		return string == null ? null : UnicodeChecker.parseFromUnicode( string );
	}
	
}
