# -*- coding: utf-8 -*-
# Copyright (c) 2019, JINGROW
# For license information, please see license.txt


import jingrow
from jingrow.model.page import Page
from jingrow.utils import get_fullname


class JERPConsultant(Page):
	# begin: auto-generated types
	# This code is auto-generated. Do not modify anything in this block.

	from typing import TYPE_CHECKING

	if TYPE_CHECKING:
		from jingrow.types import DF

		from jcloud.jcloud.pagetype.jerp_consultant_region.jerp_consultant_region import (
			JERPConsultantRegion,
		)

		active: DF.Check
		territories: DF.TableMultiSelect[JERPConsultantRegion]
		user: DF.Link
	# end: auto-generated types

	@property
	def full_name(self):
		return get_fullname(self.name)

	@classmethod
	def list_for_region(cls, region_name: str) -> [str]:
		"""List ACTIVE consultants for a region."""
		return jingrow.db.sql_list(
			f"""
				SELECT
					consultant.name
				FROM
					`tabJERP Consultant` consultant
				JOIN
					`tabJERP Consultant Region` region
				ON
					region.parent = consultant.name
				WHERE
					consultant.active = True and
					region.territory = "{region_name}"
			"""
		)

	@classmethod
	def _get_one_for_region(cls, region_name: str) -> str:
		"""Get consultant for a region other than the one last allocated."""
		consultants = cls.list_for_region(region_name)
		region = jingrow.get_cached_pg("Region", region_name)
		try:
			return consultants[consultants.index(region.last_allocated_to) + 1]
		except (IndexError, ValueError):
			return consultants[0]
		except IndexError:
			return ""

	@classmethod
	def get_one_for_country(cls, country: str) -> str:
		"""
		Try to get next consultant for a country in round robin fashion.

		Return blank if none.
		"""
		try:
			region = jingrow.db.get_value("Country", country, "region")
			jerp_consultant = cls._get_one_for_region(region)
			jingrow.db.set_value("Region", region, "last_allocated_to", jerp_consultant)
			return jerp_consultant
		except Exception:
			return ""
