# Copyright (c) 2015, JINGROW and Contributors
# License: MIT. See LICENSE

import json

import jingrow
from jingrow.core.pagetype.submission_queue.submission_queue import queue_submission
from jingrow.desk.form.load import run_onload
from jingrow.model.pagestatus import PageStatus
from jingrow.monitor import add_data_to_monitor
from jingrow.utils.scheduler import is_scheduler_inactive
from jingrow.utils.telemetry import capture_pg


@jingrow.whitelist()
def savepgs(pg, action):
	"""save / submit / update doclist"""
	pg = jingrow.get_pg(json.loads(pg))
	capture_pg(pg, action)
	if pg.get("__islocal") and pg.name.startswith("new-" + pg.pagetype.lower().replace(" ", "-")):
		# required to relink missing attachments if they exist.
		pg.__temporary_name = pg.name
	set_local_name(pg)

	# action
	pg.pagestatus = {
		"Save": PageStatus.DRAFT,
		"Submit": PageStatus.SUBMITTED,
		"Update": PageStatus.SUBMITTED,
		"Cancel": PageStatus.CANCELLED,
	}[action]

	if pg.pagestatus.is_submitted():
		if action == "Submit" and pg.meta.queue_in_background and not is_scheduler_inactive():
			queue_submission(pg, action)
			return
		pg.submit()
	else:
		pg.save()

	# update recent documents
	run_onload(pg)
	send_updated_pgs(pg)

	add_data_to_monitor(pagetype=pg.pagetype, action=action)
	status_message = "Submitted" if pg.pagestatus.is_submitted() else "Saved"
	jingrow.msgprint(jingrow._(status_message), indicator="green", alert=True)


@jingrow.whitelist()
def cancel(pagetype=None, name=None, workflow_state_fieldname=None, workflow_state=None):
	"""cancel a doclist"""
	pg = jingrow.get_pg(pagetype, name)
	capture_pg(pg, "Cancel")

	if workflow_state_fieldname and workflow_state:
		pg.set(workflow_state_fieldname, workflow_state)
	pg.cancel()
	send_updated_pgs(pg)
	jingrow.msgprint(jingrow._("Cancelled"), indicator="red", alert=True)


def send_updated_pgs(pg):
	from .load import get_pageinfo

	get_pageinfo(pg)

	d = pg.as_dict()
	if hasattr(pg, "localname"):
		d["localname"] = pg.localname

	jingrow.response.pgs.append(d)


def set_local_name(pg):
	def _set_local_name(d):
		if pg.get("__islocal") or d.get("__islocal"):
			d.localname = d.name
			d.name = None

	_set_local_name(pg)
	for child in pg.get_all_children():
		_set_local_name(child)

	if pg.get("__newname"):
		pg.name = pg.get("__newname")
