import http
import json
import os
import uuid
from io import BytesIO
from typing import Literal

from pypdf import PdfWriter

import jingrow
from jingrow import _
from jingrow.core.pagetype.access_log.access_log import make_access_log
from jingrow.translate import print_language
from jingrow.utils.deprecations import deprecated
from jingrow.utils.pdf import get_pdf

no_cache = 1

base_template_path = "www/printview.html"
standard_format = "templates/print_formats/standard.html"

from jingrow.www.printview import validate_print_permission


@jingrow.whitelist()
def download_multi_pdf(
	pagetype: str | dict[str, list[str]],
	name: str | list[str],
	format: str | None = None,
	no_letterhead: bool = False,
	letterhead: str | None = None,
	options: str | None = None,
):
	"""
	Calls _download_multi_pdf with the given parameters and returns the response
	"""
	return _download_multi_pdf(pagetype, name, format, no_letterhead, letterhead, options)


@jingrow.whitelist()
def download_multi_pdf_async(
	pagetype: str | dict[str, list[str]],
	name: str | list[str],
	format: str | None = None,
	no_letterhead: bool = False,
	letterhead: str | None = None,
	options: str | None = None,
):
	"""
	Calls _download_multi_pdf with the given parameters in a background job, returns task ID
	"""
	task_id = str(uuid.uuid4())
	if isinstance(pagetype, dict):
		pg_count = sum([len(pagetype[dt]) for dt in pagetype])
	else:
		pg_count = len(json.loads(name))

	jingrow.enqueue(
		_download_multi_pdf,
		pagetype=pagetype,
		name=name,
		task_id=task_id,
		format=format,
		no_letterhead=no_letterhead,
		letterhead=letterhead,
		options=options,
		queue="long" if pg_count > 20 else "short",
	)
	jingrow.local.response["http_status_code"] = http.HTTPStatus.CREATED
	return {"task_id": task_id}


def _download_multi_pdf(
	pagetype: str | dict[str, list[str]],
	name: str | list[str],
	format: str | None = None,
	no_letterhead: bool = False,
	letterhead: str | None = None,
	options: str | None = None,
	task_id: str | None = None,
):
	"""Return a PDF compiled by concatenating multiple documents.

	Returns a PDF compiled by concatenating multiple documents. The documents
	can be from a single PageType or multiple PageTypes

	Note: The design may seem a little weird, but it  exists to ensure backward compatibility.
	          The correct way to use this function is to pass a dict to pagetype as described below

	NEW FUNCTIONALITY
	=================
	Parameters:
	pagetype (dict):
	        key (string): PageType name
	        value (list): of strings of pg names which need to be concatenated and printed
	name (string):
	        name of the pdf which is generated
	format:
	        Print Format to be used

	Returns:
	PDF: A PDF generated by the concatenation of the mentioned input pgs

	OLD FUNCTIONALITY - soon to be deprecated
	=========================================
	Parameters:
	pagetype (string):
	        name of the PageType to which the pgs belong which need to be printed
	name (string or list):
	        If string the name of the pg which needs to be printed
	        If list the list of strings of pg names which needs to be printed
	format:
	        Print Format to be used

	Returns:
	Publishes a link to the PDF to the given task ID
	"""
	filename = ""

	pdf_writer = PdfWriter()

	if isinstance(options, str):
		options = json.loads(options)

	if not isinstance(pagetype, dict):
		result = json.loads(name)
		total_pgs = len(result)
		filename = f"{pagetype}_"

		# Concatenating pdf files
		for idx, ss in enumerate(result):
			try:
				pdf_writer = jingrow.get_print(
					pagetype,
					ss,
					format,
					as_pdf=True,
					output=pdf_writer,
					no_letterhead=no_letterhead,
					letterhead=letterhead,
					pdf_options=options,
				)
			except Exception:
				if task_id:
					jingrow.publish_realtime(task_id=task_id, message={"message": "Failed"})

			# Publish progress
			if task_id:
				jingrow.publish_progress(
					percent=(idx + 1) / total_pgs * 100,
					title=_("PDF Generation in Progress"),
					description=_("{0}/{1} complete | Please leave this tab open until completion.").format(
						idx + 1, total_pgs
					),
					task_id=task_id,
				)

		if task_id is None:
			jingrow.local.response.filename = "{pagetype}.pdf".format(
				pagetype=pagetype.replace(" ", "-").replace("/", "-")
			)

	else:
		total_pgs = sum([len(pagetype[dt]) for dt in pagetype])
		count = 1
		for pagetype_name in pagetype:
			filename += f"{pagetype_name}_"
			for pg_name in pagetype[pagetype_name]:
				try:
					pdf_writer = jingrow.get_print(
						pagetype_name,
						pg_name,
						format,
						as_pdf=True,
						output=pdf_writer,
						no_letterhead=no_letterhead,
						letterhead=letterhead,
						pdf_options=options,
					)
				except Exception:
					if task_id:
						jingrow.publish_realtime(task_id=task_id, message="Failed")
					jingrow.log_error(
						title="Error in Multi PDF download",
						message=f"Permission Error on pg {pg_name} of pagetype {pagetype_name}",
						reference_pagetype=pagetype_name,
						reference_name=pg_name,
					)

				count += 1

				if task_id:
					jingrow.publish_progress(
						percent=count / total_pgs * 100,
						title=_("PDF Generation in Progress"),
						description=_(
							"{0}/{1} complete | Please leave this tab open until completion."
						).format(count, total_pgs),
						task_id=task_id,
					)
		if task_id is None:
			jingrow.local.response.filename = f"{name}.pdf"

	with BytesIO() as merged_pdf:
		pdf_writer.write(merged_pdf)
		if task_id:
			_file = jingrow.get_pg(
				{
					"pagetype": "File",
					"file_name": f"{filename}{task_id}.pdf",
					"content": merged_pdf.getvalue(),
					"is_private": 1,
				}
			)
			_file.save()
			jingrow.publish_realtime(f"task_complete:{task_id}", message={"file_url": _file.unique_url})
		else:
			jingrow.local.response.filecontent = merged_pdf.getvalue()
			jingrow.local.response.type = "pdf"


@deprecated
def read_multi_pdf(output: PdfWriter) -> bytes:
	with BytesIO() as merged_pdf:
		output.write(merged_pdf)
		return merged_pdf.getvalue()


@jingrow.whitelist(allow_guest=True)
def download_pdf(
	pagetype: str,
	name: str,
	format=None,
	pg=None,
	no_letterhead=0,
	language=None,
	letterhead=None,
	pdf_generator: Literal["wkhtmltopdf", "chrome"] | None = None,
):
	pg = pg or jingrow.get_pg(pagetype, name)
	validate_print_permission(pg)

	with print_language(language):
		pdf_file = jingrow.get_print(
			pagetype,
			name,
			format,
			pg=pg,
			as_pdf=True,
			letterhead=letterhead,
			no_letterhead=no_letterhead,
			pdf_generator=pdf_generator,
		)

	jingrow.local.response.filename = "{name}.pdf".format(name=name.replace(" ", "-").replace("/", "-"))
	jingrow.local.response.filecontent = pdf_file
	jingrow.local.response.type = "pdf"


@jingrow.whitelist()
def report_to_pdf(html, orientation="Landscape"):
	make_access_log(file_type="PDF", method="PDF", page=html)
	jingrow.local.response.filename = "report.pdf"
	jingrow.local.response.filecontent = get_pdf(html, {"orientation": orientation})
	jingrow.local.response.type = "pdf"


@jingrow.whitelist()
def print_by_server(
	pagetype, name, printer_setting, print_format=None, pg=None, no_letterhead=0, file_path=None
):
	print_settings = jingrow.get_pg("Network Printer Settings", printer_setting)
	try:
		import cups
	except ImportError:
		jingrow.throw(_("You need to install pycups to use this feature!"))

	try:
		cups.setServer(print_settings.server_ip)
		cups.setPort(print_settings.port)
		conn = cups.Connection()
		output = PdfWriter()
		output = jingrow.get_print(
			pagetype, name, print_format, pg=pg, no_letterhead=no_letterhead, as_pdf=True, output=output
		)
		if not file_path:
			file_path = os.path.join("/", "tmp", f"jingrow-pdf-{jingrow.generate_hash()}.pdf")
		output.write(open(file_path, "wb"))
		conn.printFile(print_settings.printer_name, file_path, name, {})
	except OSError as e:
		if (
			"ContentNotFoundError" in e.message
			or "ContentOperationNotPermittedError" in e.message
			or "UnknownContentError" in e.message
			or "RemoteHostClosedError" in e.message
		):
			jingrow.throw(_("PDF generation failed"))
	except cups.IPPError:
		jingrow.throw(_("Printing failed"))
