import inspect

import influxframework

__version__ = "14.5.0"


def get_default_company(user=None):
	"""Get default company for user"""
	from influxframework.defaults import get_user_default_as_list

	if not user:
		user = influxframework.session.user

	companies = get_user_default_as_list(user, "company")
	if companies:
		default_company = companies[0]
	else:
		default_company = influxframework.db.get_single_value("Global Defaults", "default_company")

	return default_company


def get_default_currency():
	"""Returns the currency of the default company"""
	company = get_default_company()
	if company:
		return influxframework.get_cached_value("Company", company, "default_currency")


def get_default_cost_center(company):
	"""Returns the default cost center of the company"""
	if not company:
		return None

	if not influxframework.flags.company_cost_center:
		influxframework.flags.company_cost_center = {}
	if not company in influxframework.flags.company_cost_center:
		influxframework.flags.company_cost_center[company] = influxframework.get_cached_value(
			"Company", company, "cost_center"
		)
	return influxframework.flags.company_cost_center[company]


def get_company_currency(company):
	"""Returns the default company currency"""
	if not influxframework.flags.company_currency:
		influxframework.flags.company_currency = {}
	if not company in influxframework.flags.company_currency:
		influxframework.flags.company_currency[company] = influxframework.db.get_value(
			"Company", company, "default_currency", cache=True
		)
	return influxframework.flags.company_currency[company]


def set_perpetual_inventory(enable=1, company=None):
	if not company:
		company = "_Test Company" if influxframework.flags.in_test else get_default_company()

	company = influxframework.get_doc("Company", company)
	company.enable_perpetual_inventory = enable
	company.save()


def encode_company_abbr(name, company=None, abbr=None):
	"""Returns name encoded with company abbreviation"""
	company_abbr = abbr or influxframework.get_cached_value("Company", company, "abbr")
	parts = name.rsplit(" - ", 1)

	if parts[-1].lower() != company_abbr.lower():
		parts.append(company_abbr)

	return " - ".join(parts)


def is_perpetual_inventory_enabled(company):
	if not company:
		company = "_Test Company" if influxframework.flags.in_test else get_default_company()

	if not hasattr(influxframework.local, "enable_perpetual_inventory"):
		influxframework.local.enable_perpetual_inventory = {}

	if not company in influxframework.local.enable_perpetual_inventory:
		influxframework.local.enable_perpetual_inventory[company] = (
			influxframework.get_cached_value("Company", company, "enable_perpetual_inventory") or 0
		)

	return influxframework.local.enable_perpetual_inventory[company]


def get_default_finance_book(company=None):
	if not company:
		company = get_default_company()

	if not hasattr(influxframework.local, "default_finance_book"):
		influxframework.local.default_finance_book = {}

	if not company in influxframework.local.default_finance_book:
		influxframework.local.default_finance_book[company] = influxframework.get_cached_value(
			"Company", company, "default_finance_book"
		)

	return influxframework.local.default_finance_book[company]


def get_party_account_type(party_type):
	if not hasattr(influxframework.local, "party_account_types"):
		influxframework.local.party_account_types = {}

	if not party_type in influxframework.local.party_account_types:
		influxframework.local.party_account_types[party_type] = (
			influxframework.db.get_value("Party Type", party_type, "account_type") or ""
		)

	return influxframework.local.party_account_types[party_type]


def get_region(company=None):
	"""Return the default country based on flag, company or global settings

	You can also set global company flag in `influxframework.flags.company`
	"""
	if company or influxframework.flags.company:
		return influxframework.get_cached_value("Company", company or influxframework.flags.company, "country")
	elif influxframework.flags.country:
		return influxframework.flags.country
	else:
		return influxframework.get_system_settings("country")


def allow_regional(fn):
	"""Decorator to make a function regionally overridable

	Example:
	@influxerp.allow_regional
	def myfunction():
	  pass"""

	def caller(*args, **kwargs):
		overrides = influxframework.get_hooks("regional_overrides", {}).get(get_region())
		function_path = f"{inspect.getmodule(fn).__name__}.{fn.__name__}"

		if not overrides or function_path not in overrides:
			return fn(*args, **kwargs)

		# Priority given to last installed app
		return influxframework.get_attr(overrides[function_path][-1])(*args, **kwargs)

	return caller
