from models import Rules, Pools, Tasks	# pylint: disable=wildcard-import
#from common.django_model import db

# TODO: Define db operations below, example here

#@db.model_get_optional_result
#def get_item(item_id):
#	return ItemTab.objects.filter(item_id=item_id)
#
#def set_item(item_id, shop_id, name):
#	item, created = ItemTab.objects.get_or_create(item_id=item_id, defaults={'shop_id': shop_id, 'name': name})
#	if not created:
#		item.shop_id = shop_id
#		item.name = name
#		item.save()
#	return item
#
#def remove_item(item_id):
#	return ItemTab.objects.filter(item_id=item_id).delete()

## Real code here
def get_rules():
	return Rules.objects.all()

def get_rule_by_id(rule_id):
	return Rules.objects.get(pk=rule_id)

def get_active_rules():
	data = Rules.objects.filter(status=1)
	return data

def create_rule_info(conditions, aggregation_period, threshold, depends="NULL", next_trigger="NULL", name="NULL", desc="NULL", status=1):
	rule = Rules.objects.create(
		conditions=conditions,
		aggregation_period=aggregation_period,
		threshold=threshold,
		depends=depends,
		next_trigger=next_trigger,
		name=name,
		desc=desc,
		status=status
	)
	return rule

def toggle_rule_info(**kwargs):
	rule_id = kwargs['rule_id']
	rule = Rules.objects.get(pk=rule_id)
	rule.status = (rule.status + 1) % 2
	rule.save()
	return rule


def update_rule_info(**kwargs):
	rule_id = kwargs['rule_id']
	rule = Rules.objects.get(pk=rule_id)

	if rule is not None:
		for input_field, value in kwargs.items():
			if  input_field in [f.name for f in Rules._meta.fields]:
				setattr(rule, input_field, value)
		rule.save()
	return rule

def disable_rule(rule_id):
	rule = Rules.objects.get(pk=rule_id)
	rule.status=0
	rule.save()
	return rule

def enable_rule(rule_id):
	rule = Rules.objects.get(pk=rule_id)
	rule.status=1
	rule.save()
	return rule

def get_rule_by_name(name):
	return Rules.objects.get(name=name)


def remove_rule(rule_id):
	return Rules.objects.get(pk=rule_id).delete()


def set_rule_status(rule_id, status):
	r = Rules.objects.get(rule_id)
	try:
		r.status = status
		r.save()
	except ValueError as e:
		log.error(e)

def get_pools():
	return Pools.objects.all()

def get_pool_by_id(pool_id):

	try:
		return Pools.objects.get(pk=pool_id)
	except ValueError as e:
		log.error(e)


def get_default_pool():
	return get_pool_by_id(pool_id=1)

def get_tasks():
	data = Tasks.objects.all()
	return data

def get_task(task_id):
	data = Tasks.objects.get(pk=task_id)
	return data

def get_active_tasks():
	data = Tasks.objects.filter(status=1)
	return data
