# Copyright (c) 2015, XhiveFramework Technologies and contributors
# License: MIT. See LICENSE

import json

import xhiveframework
from xhiveframework import _
from xhiveframework.desk.doctype.bulk_update.bulk_update import show_progress
from xhiveframework.model.document import Document


class DeletedDocument(Document):
	pass


@xhiveframework.whitelist()
def restore(name, alert=True):
	deleted = xhiveframework.get_doc("Deleted Document", name)

	if deleted.restored:
		xhiveframework.throw(_("Document {0} Already Restored").format(name), exc=xhiveframework.DocumentAlreadyRestored)

	doc = xhiveframework.get_doc(json.loads(deleted.data))

	try:
		doc.insert()
	except xhiveframework.DocstatusTransitionError:
		xhiveframework.msgprint(_("Cancelled Document restored as Draft"))
		doc.docstatus = 0
		doc.insert()

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

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

	if alert:
		xhiveframework.msgprint(_("Document Restored"))


@xhiveframework.whitelist()
def bulk_restore(docnames):
	docnames = xhiveframework.parse_json(docnames)
	message = _("Restoring Deleted Document")
	restored, invalid, failed = [], [], []

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

		except xhiveframework.DocumentAlreadyRestored:
			xhiveframework.message_log.pop()
			invalid.append(d)

		except Exception:
			xhiveframework.message_log.pop()
			failed.append(d)
			xhiveframework.db.rollback()

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