# Copyright (c) 2018, SolutionERP LLC and contributors
# For license information, please see license.txt


from urllib.parse import urlparse

import xhiveframework
from xhiveframework import _
from xhiveframework.custom.doctype.custom_field.custom_field import create_custom_fields
from xhiveframework.model.document import Document
from xhiveframework.utils.nestedset import get_root_of


class WoocommerceSettings(Document):
	def validate(self):
		self.validate_settings()
		self.create_delete_custom_fields()
		self.create_webhook_url()

	def create_delete_custom_fields(self):
		if self.enable_sync:
			create_custom_fields(
				{
					("Customer", "Sales Order", "Item", "Address"): dict(
						fieldname="woocommerce_id",
						label="Woocommerce ID",
						fieldtype="Data",
						read_only=1,
						print_hide=1,
					),
					("Customer", "Address"): dict(
						fieldname="woocommerce_email",
						label="Woocommerce Email",
						fieldtype="Data",
						read_only=1,
						print_hide=1,
					),
				}
			)

			if not xhiveframework.get_value("Item Group", {"name": _("WooCommerce Products")}):
				item_group = xhiveframework.new_doc("Item Group")
				item_group.item_group_name = _("WooCommerce Products")
				item_group.parent_item_group = get_root_of("Item Group")
				item_group.insert()

	def validate_settings(self):
		if self.enable_sync:
			if not self.secret:
				self.set("secret", xhiveframework.generate_hash())

			if not self.woocommerce_server_url:
				xhiveframework.throw(_("Please enter Woocommerce Server URL"))

			if not self.api_consumer_key:
				xhiveframework.throw(_("Please enter API Consumer Key"))

			if not self.api_consumer_secret:
				xhiveframework.throw(_("Please enter API Consumer Secret"))

	def create_webhook_url(self):
		endpoint = "/api/method/xhiveerp.xhiveerp_integrations.connectors.woocommerce_connection.order"

		try:
			url = xhiveframework.request.url
		except RuntimeError:
			# for CI Test to work
			url = "http://localhost:8000"

		server_url = "{uri.scheme}://{uri.netloc}".format(uri=urlparse(url))

		delivery_url = server_url + endpoint
		self.endpoint = delivery_url


@xhiveframework.whitelist()
def generate_secret():
	woocommerce_settings = xhiveframework.get_doc("Woocommerce Settings")
	woocommerce_settings.secret = xhiveframework.generate_hash()
	woocommerce_settings.save()


@xhiveframework.whitelist()
def get_series():
	return {
		"sales_order_series": xhiveframework.get_meta("Sales Order").get_options("naming_series") or "SO-WOO-",
	}
