import re
import six

from django.test import TestCase
from django.conf import settings
from django.template import Context, Template

from stripejs import forms

class FormWidgetRender(TestCase):
	""" 
		Test form render
		Forms need the 'name' key removed and replaced with 'stripe-data' 
		so that no billing information gets sent to the local server
	"""

	# Setup the forms
	credit_form = forms.StripeCreditForm()
	credit_form_fields = {'number':'text', 'cvc':'number', 'exp_month':'number', 'exp_year':'number'}

	name_form = forms.StripeCreditNameForm()
	name_form_fields = {'name':'text'}

	address_form = forms.StripeCreditAddressForm()
	address_form_fields = {'address_line1':'text', 'address_line2':'text', 'address_city':'text', 'address_state':'text', 'address_zip':'number', 'address_country':'text'}

	data_stripe_regex = re.compile(".+data-stripe=\"(?P<field_name>\w+)\".+type=\"(?P<field_type>\w+)\".+value=\"(?P<field_value>\w+)\".+")

	def test_credit_form_render(self):

		for field_name, field_type in six.iteritems(self.credit_form_fields):
			render = self.credit_form.fields.get(field_name).widget.render(name=field_name, value=124)
			m = re.match(self.data_stripe_regex, render)
			self.assertEqual(m.group('field_type'), field_type)
			self.assertEqual(m.group('field_name'), field_name)

	def test_name_form_render(self):

		for field_name, field_type in six.iteritems(self.name_form_fields):
			render = self.name_form.fields.get(field_name).widget.render(name=field_name, value=124)
			m = re.match(self.data_stripe_regex, render)
			self.assertEqual(m.group('field_type'), field_type)
			self.assertEqual(m.group('field_name'), field_name)

	def test_address_form_render(self):

		for field_name, field_type in six.iteritems(self.address_form_fields):
			render = self.address_form.fields.get(field_name).widget.render(name=field_name, value=124)
			m = re.match(self.data_stripe_regex, render)
			self.assertEqual(m.group('field_type'), field_type)
			self.assertEqual(m.group('field_name'), field_name)

class TemplateTagsRender(TestCase): 

	def tag_test(self, tag, output):
		t = Template('{% load stripe_tags %}'+ tag)
		c = Context()
		self.assertEqual(t.render(c), output)

	def test_pubkey(self):
		tag = '{% stripe_public_key %}'
		output = settings.STRIPE_PUBLIC_KEY
		self.tag_test(tag,output)

	def test_js_include(self):
		tag = '{% stripe_js %}'
		output =  '<script type=\"text/javascript\" src=\"https://js.stripe.com/v2/\"></script>'
		self.tag_test(tag, output)

	def test_js_publishable_key(self):
		tag = '{% stripe_publishable_key %}'
		output = "<script type=\"text/javascript\">Stripe.setPublishableKey('%s');</script>" % settings.STRIPE_PUBLIC_KEY
		self.tag_test(tag, output)