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

import influxframework
from influxframework.model.document import Document


class Wishlist(Document):
	pass


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

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

	web_item_data = influxframework.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 influxframework.db.exists("Wishlist", influxframework.session.user):
		# initialise wishlist
		wishlist = influxframework.get_doc({"doctype": "Wishlist"})
		wishlist.user = influxframework.session.user
		wishlist.append("items", wished_item_dict)
		wishlist.save(ignore_permissions=True)
	else:
		wishlist = influxframework.get_doc("Wishlist", influxframework.session.user)
		item = wishlist.append("items", wished_item_dict)
		item.db_insert()

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


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

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

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