import json

import jingrow
from jingrow.core.pagetype.file.file import File
from jingrow.core.pagetype.file.utils import setup_folder_path
from jingrow.utils import cint, cstr


@jingrow.whitelist()
def unzip_file(name: str):
	"""Unzip the given file and make file records for each of the extracted files"""
	file: File = jingrow.get_pg("File", name)
	return file.unzip()


@jingrow.whitelist()
def get_attached_images(pagetype: str, names: list[str] | str) -> jingrow._dict:
	"""get list of image urls attached in form
	returns {name: ['image.jpg', 'image.png']}"""

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

	img_urls = jingrow.db.get_list(
		"File",
		filters={
			"attached_to_pagetype": pagetype,
			"attached_to_name": ("in", names),
			"is_folder": 0,
		},
		fields=["file_url", "attached_to_name as pagename"],
	)

	out = jingrow._dict()
	for i in img_urls:
		out[i.pagename] = out.get(i.pagename, [])
		out[i.pagename].append(i.file_url)

	return out


@jingrow.whitelist()
def get_files_in_folder(folder: str, start: int = 0, page_length: int = 20) -> dict:
	attachment_folder = jingrow.db.get_value(
		"File",
		"Home/Attachments",
		["name", "file_name", "file_url", "is_folder", "modified"],
		as_dict=1,
	)

	files = jingrow.get_list(
		"File",
		{"folder": folder},
		["name", "file_name", "file_url", "is_folder", "modified"],
		start=start,
		page_length=page_length + 1,
	)

	if folder == "Home" and attachment_folder not in files:
		files.insert(0, attachment_folder)

	return {"files": files[:page_length], "has_more": len(files) > page_length}


@jingrow.whitelist()
def get_files_by_search_text(text: str) -> list[dict]:
	if not text:
		return []

	text = "%" + cstr(text).lower() + "%"
	return jingrow.get_list(
		"File",
		fields=["name", "file_name", "file_url", "is_folder", "modified"],
		filters={"is_folder": False},
		or_filters={
			"file_name": ("like", text),
			"file_url": text,
			"name": ("like", text),
		},
		order_by="modified desc",
		limit=20,
	)


@jingrow.whitelist(allow_guest=True)
def get_max_file_size() -> int:
	return (
		cint(jingrow.get_system_settings("max_file_size")) * 1024 * 1024
		or cint(jingrow.conf.get("max_file_size"))
		or 25 * 1024 * 1024
	)


@jingrow.whitelist()
def create_new_folder(file_name: str, folder: str) -> File:
	"""create new folder under current parent folder"""
	file = jingrow.new_pg("File")
	file.file_name = file_name
	file.is_folder = 1
	file.folder = folder
	file.insert(ignore_if_duplicate=True)
	return file


@jingrow.whitelist()
def move_file(file_list: list[File | dict] | str, new_parent: str, old_parent: str) -> None:
	if isinstance(file_list, str):
		file_list = json.loads(file_list)

	# will check for permission on each file & update parent
	for file_obj in file_list:
		setup_folder_path(file_obj.get("name"), new_parent)

	# recalculate sizes
	jingrow.get_pg("File", old_parent).save()
	jingrow.get_pg("File", new_parent).save()


@jingrow.whitelist()
def zip_files(files: str):
	files = jingrow.parse_json(files)
	jingrow.response["filename"] = "files.zip"
	jingrow.response["filecontent"] = File.zip_files(files)
	jingrow.response["type"] = "download"
