# -*- coding: utf-8 -*-
# Copyright (c) 2021, SolutionERP LLC and contributors
# For license information, please see license.txt

import xhiveframework
from xhiveframework.model.document import Document


class Wishlist(Document):
	pass


@xhiveframework.whitelist()
def add_to_wishlist(item_code):
	"""Insert Item into wishlist."""

	if xhiveframework.db.exists("Wishlist Item", {"item_code": item_code, "parent": xhiveframework.session.user}):
		return

	web_item_data = xhiveframework.db.get_value(
		"Website Item",
		{"item_code": item_code},
		[
			"website_image",
			"website_warehouse",
			"name",
			"web_item_name",
			"item_name",
			"item_group",
			"route",
		],
		as_dict=1,
	)

	wished_item_dict = {
		"item_code": item_code,
		"item_name": web_item_data.get("item_name"),
		"item_group": web_item_data.get("item_group"),
		"website_item": web_item_data.get("name"),
		"web_item_name": web_item_data.get("web_item_name"),
		"image": web_item_data.get("website_image"),
		"warehouse": web_item_data.get("website_warehouse"),
		"route": web_item_data.get("route"),
	}

	if not xhiveframework.db.exists("Wishlist", xhiveframework.session.user):
		# initialise wishlist
		wishlist = xhiveframework.get_doc({"doctype": "Wishlist"})
		wishlist.user = xhiveframework.session.user
		wishlist.append("items", wished_item_dict)
		wishlist.save(ignore_permissions=True)
	else:
		wishlist = xhiveframework.get_doc("Wishlist", xhiveframework.session.user)
		item = wishlist.append("items", wished_item_dict)
		item.db_insert()

	if hasattr(xhiveframework.local, "cookie_manager"):
		xhiveframework.local.cookie_manager.set_cookie("wish_count", str(len(wishlist.items)))


@xhiveframework.whitelist()
def remove_from_wishlist(item_code):
	if xhiveframework.db.exists("Wishlist Item", {"item_code": item_code, "parent": xhiveframework.session.user}):
		xhiveframework.db.delete("Wishlist Item", {"item_code": item_code, "parent": xhiveframework.session.user})
		xhiveframework.db.commit()  # nosemgrep

		wishlist_items = xhiveframework.db.get_values("Wishlist Item", filters={"parent": xhiveframework.session.user})

		if hasattr(xhiveframework.local, "cookie_manager"):
			xhiveframework.local.cookie_manager.set_cookie("wish_count", str(len(wishlist_items)))
