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

import json

import jingrow
from jingrow import _
from jingrow.desk.pagetype.bulk_update.bulk_update import show_progress
from jingrow.model.page import Page
from jingrow.model.workflow import get_workflow_name


class DeletedPage(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

		data: DF.Code | None
		deleted_pagetype: DF.Data | None
		deleted_name: DF.Data | None
		new_name: DF.ReadOnly | None
		restored: DF.Check
	# end: auto-generated types

	no_feed_on_delete = True

	@staticmethod
	def clear_old_logs(days=180):
		from jingrow.query_builder import Interval
		from jingrow.query_builder.functions import Now

		table = jingrow.qb.PageType("Deleted Page")
		jingrow.db.delete(table, filters=(table.modified < (Now() - Interval(days=days))))


@jingrow.whitelist()
def restore(name, alert=True):
	deleted = jingrow.get_pg("Deleted Page", name)

	if deleted.restored:
		jingrow.throw(_("Page {0} Already Restored").format(name), exc=jingrow.PageAlreadyRestored)

	pg = jingrow.get_pg(json.loads(deleted.data))

	try:
		pg.insert()
	except jingrow.PagestatusTransitionError:
		jingrow.msgprint(_("Cancelled Page restored as Draft"))
		pg.pagestatus = 0
		active_workflow = get_workflow_name(pg.pagetype)
		if active_workflow:
			workflow_state_fieldname = jingrow.get_value("Workflow", active_workflow, "workflow_state_field")
			if pg.get(workflow_state_fieldname):
				pg.set(workflow_state_fieldname, None)
		pg.insert()

	pg.add_comment("Restore", _("restored {0} as {1}").format(deleted.deleted_name, pg.name))

	deleted.new_name = pg.name
	deleted.restored = 1
	deleted.db_update()

	if alert:
		jingrow.msgprint(_("Page Restored"))


@jingrow.whitelist()
def bulk_restore(pagenames):
	pagenames = jingrow.parse_json(pagenames)
	message = _("Restoring Deleted Page")
	restored, invalid, failed = [], [], []

	for i, d in enumerate(pagenames):
		try:
			show_progress(pagenames, message, i + 1, d)
			restore(d, alert=False)
			jingrow.db.commit()
			restored.append(d)

		except jingrow.PageAlreadyRestored:
			jingrow.clear_last_message()
			invalid.append(d)

		except Exception:
			jingrow.clear_last_message()
			failed.append(d)
			jingrow.db.rollback()

	return {"restored": restored, "invalid": invalid, "failed": failed}
