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

import json

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


class DeletedDocument(Document):
	pass


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

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

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

	try:
		doc.insert()
	except influxframework.DocstatusTransitionError:
		influxframework.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:
		influxframework.msgprint(_("Document Restored"))


@influxframework.whitelist()
def bulk_restore(docnames):
	docnames = influxframework.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)
			influxframework.db.commit()
			restored.append(d)

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

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

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