# Copyright (c) 2015, JINGROW and Contributors
# License: MIT. See LICENSE
import json
from collections import defaultdict
from typing import TYPE_CHECKING, Union

import jingrow
from jingrow import _
from jingrow.model.pagestatus import PageStatus
from jingrow.utils import cint

if TYPE_CHECKING:
	from jingrow.model.page import Page
	from jingrow.workflow.pagetype.workflow.workflow import Workflow


class WorkflowStateError(jingrow.ValidationError):
	pass


class WorkflowTransitionError(jingrow.ValidationError):
	pass


class WorkflowPermissionError(jingrow.ValidationError):
	pass


def get_workflow_name(pagetype):
	workflow_name = jingrow.cache.hget("workflow", pagetype)
	if workflow_name is None:
		workflow_name = jingrow.db.get_value("Workflow", {"document_type": pagetype, "is_active": 1}, "name")
		jingrow.cache.hset("workflow", pagetype, workflow_name or "")

	return workflow_name


@jingrow.whitelist()
def get_transitions(
	pg: Union["Page", str, dict], workflow: "Workflow" = None, raise_exception: bool = False
) -> list[dict]:
	"""Return list of possible transitions for the given pg"""
	from jingrow.model.page import Page

	if not isinstance(pg, Page):
		pg = jingrow.get_pg(jingrow.parse_json(pg))
		pg.load_from_db()

	if pg.is_new():
		return []

	pg.check_permission("read")

	workflow = workflow or get_workflow(pg.pagetype)
	current_state = pg.get(workflow.workflow_state_field)

	if not current_state:
		if raise_exception:
			raise WorkflowStateError
		else:
			jingrow.throw(_("Workflow State not set"), WorkflowStateError)

	transitions = []
	roles = jingrow.get_roles()

	for transition in workflow.transitions:
		if transition.state == current_state and transition.allowed in roles:
			if not is_transition_condition_satisfied(transition, pg):
				continue
			transitions.append(transition.as_dict())

	return transitions


def get_workflow_safe_globals():
	# access to jingrow.db.get_value, jingrow.db.get_list, and date time utils.
	return dict(
		jingrow=jingrow._dict(
			db=jingrow._dict(get_value=jingrow.db.get_value, get_list=jingrow.db.get_list),
			session=jingrow.session,
			utils=jingrow._dict(
				now_datetime=jingrow.utils.now_datetime,
				add_to_date=jingrow.utils.add_to_date,
				get_datetime=jingrow.utils.get_datetime,
				now=jingrow.utils.now,
			),
		)
	)


def is_transition_condition_satisfied(transition, pg) -> bool:
	if not transition.condition:
		return True
	else:
		return jingrow.safe_eval(transition.condition, get_workflow_safe_globals(), dict(pg=pg.as_dict()))


@jingrow.whitelist()
def apply_workflow(pg, action):
	"""Allow workflow action on the current pg"""
	pg = jingrow.get_pg(jingrow.parse_json(pg))
	pg.load_from_db()
	workflow = get_workflow(pg.pagetype)
	transitions = get_transitions(pg, workflow)
	user = jingrow.session.user

	# find the transition
	transition = None
	for t in transitions:
		if t.action == action:
			transition = t

	if not transition:
		jingrow.throw(_("Not a valid Workflow Action"), WorkflowTransitionError)

	if not has_approval_access(user, pg, transition):
		jingrow.throw(_("Self approval is not allowed"))

	# update workflow state field
	pg.set(workflow.workflow_state_field, transition.next_state)

	# find settings for the next state
	next_state = next(d for d in workflow.states if d.state == transition.next_state)

	# update any additional field
	if next_state.update_field:
		pg.set(next_state.update_field, next_state.update_value)

	new_pagestatus = PageStatus(next_state.pg_status or 0)
	if pg.pagestatus.is_draft() and new_pagestatus.is_draft():
		pg.save()
	elif pg.pagestatus.is_draft() and new_pagestatus.is_submitted():
		from jingrow.core.pagetype.submission_queue.submission_queue import queue_submission
		from jingrow.utils.scheduler import is_scheduler_inactive

		if pg.meta.queue_in_background and not is_scheduler_inactive():
			queue_submission(pg, "Submit")
			return

		pg.submit()
	elif pg.pagestatus.is_submitted() and new_pagestatus.is_submitted():
		pg.save()
	elif pg.pagestatus.is_submitted() and new_pagestatus.is_cancelled():
		pg.cancel()
	else:
		jingrow.throw(_("Illegal Page Status for {0}").format(next_state.state))

	pg.add_comment("Workflow", _(next_state.state))

	return pg


@jingrow.whitelist()
def can_cancel_document(pagetype):
	workflow = get_workflow(pagetype)
	cancelling_states = [s.state for s in workflow.states if s.pg_status == "2"]
	if not cancelling_states:
		return True

	for transition in workflow.transitions:
		if transition.next_state in cancelling_states:
			return False
	return True


def validate_workflow(pg):
	"""Validate Workflow State and Transition for the current user.

	- Check if user is allowed to edit in current state
	- Check if user is allowed to transition to the next state (if changed)
	"""
	workflow = get_workflow(pg.pagetype)

	current_state = None
	if getattr(pg, "_pg_before_save", None):
		current_state = pg._pg_before_save.get(workflow.workflow_state_field)
	next_state = pg.get(workflow.workflow_state_field)

	if not next_state:
		next_state = workflow.states[0].state
		pg.set(workflow.workflow_state_field, next_state)

	if not current_state:
		current_state = workflow.states[0].state

	state_row = [d for d in workflow.states if d.state == current_state]
	if not state_row:
		jingrow.throw(
			_("{0} is not a valid Workflow State. Please update your Workflow and try again.").format(
				jingrow.bold(current_state)
			)
		)
	state_row = state_row[0]

	# if transitioning, check if user is allowed to transition
	if current_state != next_state:
		bold_current = jingrow.bold(current_state)
		bold_next = jingrow.bold(next_state)

		if not pg._pg_before_save:
			# transitioning directly to a state other than the first
			# e.g from data import
			jingrow.throw(
				_("Workflow State transition not allowed from {0} to {1}").format(bold_current, bold_next),
				WorkflowPermissionError,
			)

		transitions = get_transitions(pg._pg_before_save)
		transition = [d for d in transitions if d.next_state == next_state]
		if not transition:
			jingrow.throw(
				_("Workflow State transition not allowed from {0} to {1}").format(bold_current, bold_next),
				WorkflowPermissionError,
			)


def get_workflow(pagetype) -> "Workflow":
	return jingrow.get_cached_pg("Workflow", get_workflow_name(pagetype))


def has_approval_access(user, pg, transition):
	return user == "Administrator" or transition.get("allow_self_approval") or user != pg.get("owner")


def get_workflow_state_field(workflow_name):
	return get_workflow_field_value(workflow_name, "workflow_state_field")


def send_email_alert(workflow_name):
	return get_workflow_field_value(workflow_name, "send_email_alert")


def get_workflow_field_value(workflow_name, field):
	return jingrow.get_cached_value("Workflow", workflow_name, field)


@jingrow.whitelist()
def bulk_workflow_approval(pagenames, pagetype, action):
	pagenames = json.loads(pagenames)
	if len(pagenames) < 20:
		_bulk_workflow_action(pagenames, pagetype, action)
	elif len(pagenames) <= 500:
		jingrow.msgprint(_("Bulk {0} is enqueued in background.").format(action), alert=True)
		jingrow.enqueue(
			_bulk_workflow_action,
			pagenames=pagenames,
			pagetype=pagetype,
			action=action,
			queue="short",
			timeout=1000,
		)
	else:
		jingrow.throw(_("Bulk approval only support up to 500 documents."), title=_("Too Many Documents"))


def _bulk_workflow_action(pagenames, pagetype, action):
	# dictionaries for logging
	failed_transactions = defaultdict(list)
	successful_transactions = defaultdict(list)

	jingrow.clear_messages()
	for idx, pagename in enumerate(pagenames, 1):
		message_dict = {}
		try:
			show_progress(pagenames, _("Applying: {0}").format(action), idx, pagename)
			apply_workflow(jingrow.get_pg(pagetype, pagename), action)
			jingrow.db.commit()
		except Exception as e:
			if not jingrow.message_log:
				# Exception is	raised manually and not from msgprint or throw
				message = f"{e.__class__.__name__}"
				if e.args:
					message += f" : {e.args[0]}"
				message_dict = {"pagename": pagename, "message": message}
				failed_transactions[pagename].append(message_dict)

			jingrow.db.rollback()
			jingrow.log_error(
				title=f"Workflow {action} threw an error for {pagetype} {pagename}",
				reference_pagetype="Workflow",
				reference_name=action,
			)
		finally:
			if not message_dict:
				if jingrow.message_log:
					messages = jingrow.get_message_log()
					for message in messages:
						jingrow.message_log.pop()
						message_dict = {"pagename": pagename, "message": message.get("message")}

						if message.get("raise_exception", False):
							failed_transactions[pagename].append(message_dict)
						else:
							successful_transactions[pagename].append(message_dict)
				else:
					successful_transactions[pagename].append({"pagename": pagename, "message": None})

	if failed_transactions and successful_transactions:
		indicator = "orange"
	elif failed_transactions:
		indicator = "red"
	else:
		indicator = "green"

	print_workflow_log(failed_transactions, _("Failed Transactions"), pagetype, indicator)
	print_workflow_log(successful_transactions, _("Successful Transactions"), pagetype, indicator)


def print_workflow_log(messages, title, pagetype, indicator):
	if messages.keys():
		msg = f"<h4>{title}</h4>"

		for pg in messages.keys():
			if len(messages[pg]):
				html = f"<details><summary>{jingrow.utils.get_link_to_form(pagetype, pg)}</summary>"
				for log in messages[pg]:
					if log.get("message"):
						html += "<div class='small text-muted' style='padding:2.5px'>{}</div>".format(
							log.get("message")
						)
				html += "</details>"
			else:
				html = f"<div>{pg}</div>"
			msg += html

		jingrow.msgprint(
			msg, title=_("Workflow Status"), indicator=indicator, is_minimizable=True, realtime=True
		)


@jingrow.whitelist()
def get_common_transition_actions(pgs, pagetype):
	common_actions = []
	if isinstance(pgs, str):
		pgs = json.loads(pgs)
	try:
		for i, pg in enumerate(pgs, 1):
			if not pg.get("pagetype"):
				pg["pagetype"] = pagetype
			actions = [
				t.get("action")
				for t in get_transitions(pg, raise_exception=True)
				if has_approval_access(jingrow.session.user, pg, t)
			]
			if not actions:
				return []
			common_actions = actions if i == 1 else set(common_actions).intersection(actions)
			if not common_actions:
				return []
	except WorkflowStateError:
		pass

	return list(common_actions)


def show_progress(pagenames, message, i, description):
	n = len(pagenames)
	if n >= 5:
		jingrow.publish_progress(float(i) * 100 / n, title=message, description=description)


def set_workflow_state_on_action(pg, workflow_name, action):
	workflow = jingrow.get_pg("Workflow", workflow_name)
	workflow_state_field = workflow.workflow_state_field

	# If workflow state of pg is already correct, don't set workflow state
	for state in workflow.states:
		if state.state == pg.get(workflow_state_field) and pg.pagestatus == cint(state.pg_status):
			return

	action_map = {"update_after_submit": "1", "submit": "1", "cancel": "2"}
	pagestatus = action_map[action]
	for state in workflow.states:
		if state.pg_status == pagestatus:
			pg.set(workflow_state_field, state.state)
			return
