"""
Generated by <Python Project Utils>
Visit the project in http://code.google.com/p/python-project-utils/
"""

from .. import connection

class FinderMetaclass(type):
	def exists(cls, primary_key = None, criteria = None):
		connector = connection.ConnectionManager.instance.connector

		if primary_key is not None or criteria is not None:
			if primary_key is not None:
				criteria = {cls.primary_key : primary_key}

			return connector.table_record_exists(cls.table_name, criteria)
		else:
			return connector.execute_table_operation(cls.table_name, connector.count, cls.primary_key) > 0

	def find(cls, primary_key):
		return cls._get_records({cls.primary_key : primary_key}, None if type(primary_key) is list else 1)

	def find_by(cls, **kargs):
		return cls._get_records(kargs, 1)

	def first(cls, limit = 1):
		return cls._get_records(limit=limit, order_by={cls.primary_key : "ASC"})

	def last(cls, limit = 1):
		return cls._get_records(limit=limit, order_by={cls.primary_key : "DESC"})

	def take(cls, limit = 1):
		return cls._get_records(limit=limit)

	def _get_records(cls, criteria = None, limit = None, order_by = None):
		records = connection.ConnectionManager.instance.connector.get_table_records(cls.table_name, criteria, limit, order_by)

		if limit == 1:
			if len(records) > 0:
				return records[0]
			else:
				return None
		else:
			return records
