# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt

from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.boot import get_allowed_pages

@frappe.whitelist()
def get(module):
	"""Returns data (sections, list of reports, counts) to render module view in desk:
	`/desk/#Module/[name]`."""
	data = get_data(module)

	out = {
		"data": data
	}

	return out

def get_data(module):
	"""Get module data for the module view `desk/#Module/[name]`"""
	doctype_info = get_doctype_info(module)
	data = build_config_from_file(module)

	if not data:
		data = build_standard_config(module, doctype_info)
	else:
		add_custom_doctypes(data, doctype_info)

	add_section(data, _("Custom Reports"), "icon-list-alt",
		get_report_list(module))

	data = combine_common_sections(data)
	data = apply_permissions(data)

	set_last_modified(data)

	return data

def build_config_from_file(module):
	"""Build module info from `app/config/desktop.py` files."""
	data = []
	module = frappe.scrub(module)

	for app in frappe.get_installed_apps():
		try:
			data += get_config(app, module)
		except ImportError:
			pass

	return data

def build_standard_config(module, doctype_info):
	"""Build standard module data from DocTypes."""
	if not frappe.db.get_value("Module Def", module):
		frappe.throw(_("Module Not Found"))

	data = []

	add_section(data, _("Documents"), "icon-star",
		[d for d in doctype_info if d.document_type in ("Document", "Transaction")])

	add_section(data, _("Setup"), "icon-cog",
		[d for d in doctype_info if d.document_type in ("Master", "Setup", "")])

	add_section(data, _("Standard Reports"), "icon-list",
		get_report_list(module, is_standard="Yes"))

	return data

def add_section(data, label, icon, items):
	"""Adds a section to the module data."""
	if not items: return
	data.append({
		"label": label,
		"icon": icon,
		"items": items
	})


def add_custom_doctypes(data, doctype_info):
	"""Adds Custom DocTypes to modules setup via `config/desktop.py`."""
	add_section(data, _("Documents"), "icon-star",
		[d for d in doctype_info if (d.custom and d.document_type in ("Document", "Transaction"))])

	add_section(data, _("Setup"), "icon-cog",
		[d for d in doctype_info if (d.custom and d.document_type in ("Setup", "Master", ""))])

def get_doctype_info(module):
	"""Returns list of non child DocTypes for given module."""
	doctype_info = frappe.db.sql("""select "doctype" as type, name, description,
		ifnull(document_type, "") as document_type, custom as custom,
		issingle as issingle
		from `tabDocType` where module=%s and istable=0
		order by custom asc, document_type desc, name asc""", module, as_dict=True)

	for d in doctype_info:
		d.description = _(d.description or "")

	return doctype_info

def combine_common_sections(data):
	"""Combine sections declared in separate apps."""
	sections = []
	sections_dict = {}
	for each in data:
		if each["label"] not in sections_dict:
			sections_dict[each["label"]] = each
			sections.append(each)
		else:
			sections_dict[each["label"]]["items"] += each["items"]

	return sections

def apply_permissions(data):
	default_country = frappe.db.get_default("country")

	user = frappe.get_user()
	user.build_permissions()

	allowed_pages = get_allowed_pages()

	new_data = []
	for section in data:
		new_items = []

		for item in (section.get("items") or []):
			item = frappe._dict(item)

			if item.country and item.country!=default_country:
				continue

			if ((item.type=="doctype" and item.name in user.can_read)
				or (item.type=="page" and item.name in allowed_pages)
				or (item.type=="report" and item.doctype in user.can_get_report)
				or item.type=="help"):

				new_items.append(item)

		if new_items:
			new_section = section.copy()
			new_section["items"] = new_items