package ollie;

import android.database.Cursor;
import android.provider.BaseColumns;
import ollie.annotation.AutoIncrement;
import ollie.annotation.Column;
import ollie.annotation.PrimaryKey;

import java.util.List;

public abstract class Model {
	@Column(BaseColumns._ID)
	@PrimaryKey
	@AutoIncrement
	public Long id;

	public static final <T extends Model> T find(Class<T> cls, Long id) {
		List<T> result = Ollie.query(cls, false, null, BaseColumns._ID + "=?", new String[]{id.toString()}, null, null, null, "1");
		if (result.size() > 0) {
			return result.get(0);
		}
		return null;
	}

	public final void load(Cursor cursor) {
		beforeLoad();
		Ollie.load(this, cursor);
		Ollie.putEntity(this);
		afterLoad();
	}

	public final Long save() {
		beforeSave();
		id = Ollie.save(this);
		Ollie.putEntity(this);
		notifyChange();
		afterSave();
		return id;
	}

	public final void delete() {
		beforeDelete();
		Ollie.delete(this);
		Ollie.removeEntity(this);
		notifyChange();
		id = null;
		afterDelete();
	}

	protected void beforeLoad() {
	}

	protected void afterLoad() {
	}

	protected void beforeSave() {
	}

	protected void afterSave() {
	}

	protected void beforeDelete() {
	}

	protected void afterDelete() {
	}

	private void notifyChange() {
		if (OllieProvider.isImplemented()) {
			Ollie.getContext().getContentResolver().notifyChange(OllieProvider.createUri(getClass(), id), null);
		}
	}

	@Override
	public boolean equals(Object obj) {
		if (obj instanceof Model && id != null) {
			final Model other = (Model) obj;
			return Ollie.getTableName(getClass()).equals(Ollie.getTableName(other.getClass())) && id.equals(other.id);
		}
		return this == obj;
	}

	@Override
	public int hashCode() {
		int hash = 1;
		hash = hash * 17 + getClass().getName().hashCode();
		hash = hash * 31 + (id != null ? id.intValue() : super.hashCode());
		return hash;
	}
}
@@ -630,24 +630,8 @@
 ) %7B%0A
-%09%09beforeLoad();%0A
 %09%09Ol
@@ -654,16 +654,16 @@
 ursor);%0A
+
 %09%09Ollie.
@@ -683,23 +683,8 @@
 s);%0A
-%09%09afterLoad();%0A
 %09%7D%0A%0A
@@ -715,24 +715,8 @@
 ) %7B%0A
-%09%09beforeSave();%0A
 %09%09id
@@ -783,23 +783,8 @@
 ();%0A
-%09%09afterSave();%0A
 %09%09re
@@ -830,26 +830,8 @@
 ) %7B%0A
-%09%09beforeDelete();%0A
 %09%09Ol
@@ -894,16 +894,16 @@
 ange();%0A
+
 %09%09id = n
@@ -911,236 +911,8 @@
 ll;%0A
-%09%09afterDelete();%0A%09%7D%0A%0A%09protected void beforeLoad() %7B%0A%09%7D%0A%0A%09protected void afterLoad() %7B%0A%09%7D%0A%0A%09protected void beforeSave() %7B%0A%09%7D%0A%0A%09protected void afterSave() %7B%0A%09%7D%0A%0A%09protected void beforeDelete() %7B%0A%09%7D%0A%0A%09protected void afterDelete() %7B%0A
 %09%7D%0A%0A

Remove model callbacks for now.