# Copyright (c) 2015, InfluxFramework LLC
# License: MIT. See LICENSE
import json

import influxframework
from influxframework.tests.utils import InfluxFrameworkTestCase
from influxframework.utils import set_request
from influxframework.website.doctype.web_form.web_form import accept
from influxframework.website.serve import get_response_content

test_dependencies = ["Web Form"]


class TestWebForm(InfluxFrameworkTestCase):
	def setUp(self):
		influxframework.conf.disable_website_cache = True
		influxframework.local.path = None

	def tearDown(self):
		influxframework.conf.disable_website_cache = False
		influxframework.local.path = None
		influxframework.local.request_ip = None
		influxframework.form_dict.web_form = None
		influxframework.form_dict.data = None
		influxframework.form_dict.docname = None

	def test_accept(self):
		influxframework.set_user("Administrator")

		doc = {
			"doctype": "Event",
			"subject": "_Test Event Web Form",
			"description": "_Test Event Description",
			"starts_on": "2014-09-09",
		}

		influxframework.form_dict.web_form = "manage-events"
		influxframework.form_dict.data = json.dumps(doc)
		influxframework.local.request_ip = "127.0.0.1"

		accept(web_form="manage-events", data=json.dumps(doc))

		self.event_name = influxframework.db.get_value("Event", {"subject": "_Test Event Web Form"})
		self.assertTrue(self.event_name)

	def test_edit(self):
		self.test_accept()

		doc = {
			"doctype": "Event",
			"subject": "_Test Event Web Form",
			"description": "_Test Event Description 1",
			"starts_on": "2014-09-09",
			"name": self.event_name,
		}

		self.assertNotEqual(
			influxframework.db.get_value("Event", self.event_name, "description"), doc.get("description")
		)

		influxframework.form_dict.web_form = "manage-events"
		influxframework.form_dict.docname = self.event_name
		influxframework.form_dict.data = json.dumps(doc)

		accept(web_form="manage-events", docname=self.event_name, data=json.dumps(doc))

		self.assertEqual(
			influxframework.db.get_value("Event", self.event_name, "description"), doc.get("description")
		)

	def test_webform_render(self):
		set_request(method="GET", path="manage-events/new")
		content = get_response_content("manage-events/new")
		self.assertIn('<h1 class="ellipsis">New Manage Events</h1>', content)
		self.assertIn('data-doctype="Web Form"', content)
		self.assertIn('data-path="manage-events/new"', content)
		self.assertIn('source-type="Generator"', content)
