# -*- coding: utf-8 -*-
# Copyright (c) 2020, Frappe Technologies and contributors
# For license information, please see license.txt

from __future__ import unicode_literals
import frappe
from frappe.model.document import Document

class NumberCard(Document):
	pass


def get_permission_query_conditions(user):

	if not user:
		user = frappe.session.user

	if user == 'Administrator':
		return

	roles = frappe.get_roles(user)
	if "System Manager" in roles:
		return None

	allowed_doctypes = tuple(frappe.permissions.get_doctypes_with_read())

	return '''
			`tabNumber Card`.`document_type` in {allowed_doctypes}
		'''.format(
			allowed_doctypes=allowed_doctypes,
		)

def has_permission(doc, ptype, user):
	roles = frappe.get_roles(user)
	if "System Manager" in roles:
		return True

	allowed_doctypes = tuple(frappe.permissions.get_doctypes_with_read())
	if doc.document_type in allowed_doctypes:
		return True

	return False

@frappe.whitelist()
def get_result(doc, to_date=None):
	doc = frappe.parse_json(doc)
	fields = []
	sql_function_map = {
		'Count': 'count',
		'Sum': 'sum',
		'Average': 'avg',
		'Minimum': 'min',
		'Maximum': 'max'
	}

	function = sql_function_map[doc.function]

	if function == 'count':
		fields = ['{function}(*) as result'.format(function=function)]
	else:
		fields = ['{function}({based_on}) as result'.format(function=function, based_on=doc.aggregate_function_based_on)]

	filters = frappe.parse_json(doc.filters_json)

	if to_date:
		filters.append([doc.document_type, 'creation', '<', to_date, False])

	number = frappe.db.get_all(doc.document_type, fields = fields, filters = filters)[0]['result']

	frappe.db.set_value('Number Card', doc.name, 'previous_result', number)
	return number

@frappe.whitelist()
def get_percentage_difference(doc, result):
	doc = frappe.parse_json(doc)
	result = frappe.parse_json(result)

	doc = frappe.get_doc('Number Card', doc.name)

	if not doc.get('show_percentage_stats'):
		return

	previous_result = calculate_previous_result(doc)
	difference = (result - previous_result)/100.0

	return difference


def calculate_previous_result(doc):
	from frappe.utils import add_to_date

	current_date = frappe.utils.now()
	if doc.stats_time_interval == 'Daily':
		previous_date = add_to_date(current_date, days=-1)
	elif doc.stats_time_interval == 'Weekly':
		previous_date = add_to_date(current_date, weeks=-1)
	elif doc.stats_time_interval == 'Monthly':
		previous_date = add_to_date(current_date, months=-1)
	else:
		previous_date = add_to_date(current_date, years=-1)

	number = get_result(doc, previous_date)
	return number

@frappe.whitelist()
def create_number_card(args):
	args = frappe.parse_json(args)
	doc = frappe.new_doc('Number Card')

	doc.update(args)
	doc.insert(ignore_permissions=True)
	return doc

def get_cards_for_user(doctype, txt, searchfield, start, page_len, filters):
	or_filters = {'owner': frappe.session.user, 'is_public': 1}
	return frappe.db.get_list('Number Card',
		fields=['name', 'label'],
		filters=filters,
		or_filters=or_filters,
		as_list = 1)
@@ -2859,192 +2859,895 @@
 ):%0A%09
-or_filters = %7B'owner': frappe.session.user, 'is_public': 1%7D%0A%09return frappe.db.get_list('Number Card',%0A%09%09fields=%5B'name', 'label'%5D,%0A%09%09filters=filters,%0A%09%09or_filters=or_filters,%0A%09%09as_list = 1)
+meta = frappe.get_meta(doctype)%0A%09searchfields = meta.get_search_fields()%0A%09search_conditions = %5B%5D%0A%0A%09if txt:%0A%09%09for field in searchfields:%0A%09%09%09search_conditions.append('%60tab%7Bdoctype%7D%60.%60%7Bfield%7D%60 like %25(txt)s'.format(field=field, doctype=doctype, txt=txt))%0A%0A%09%09search_conditions = ' or '.join(search_conditions)%0A%0A%09search_conditions = 'and (' + search_conditions +')' if search_conditions else ''%0A%09conditions, values = frappe.db.build_conditions(filters)%0A%09values%5B'txt'%5D = '%25' + txt + '%25'%0A%0A%09return frappe.db.sql(%0A%09%09'''select%0A%09%09%09%60tabNumber Card%60.name, %60tabNumber Card%60.label, %60tabNumber Card%60.document_type%0A%09%09from%0A%09%09%09%60tabNumber Card%60%0A%09%09where%0A%09%09%09%7Bconditions%7D and%0A%09%09%09(%60tabNumber Card%60.owner = '%7Buser%7D' or%0A%09%09%09%60tabNumber Card%60.is_public = 1)%0A%09%09%09%7Bsearch_conditions%7D%0A%09'''.format(%0A%09%09filters=filters,%0A%09%09user = frappe.session.user,%0A%09%09search_conditions = search_conditions,%0A%09%09conditions=conditions%0A%09), values)%0A%0A

add search fields to number cards link query