# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import webapp2
from valid_month import valid_month as vm
from valid_day import valid_day as vd
from valid_year import valid_year as vy
from escape_html import escape_html as es

form="""
<form method="post">
	What is your birthday?
    <br>
    <label> Month <input type="text" name="month" value="%(month)s"> </label>
    <label> Day <input type="text" name="day" value="%(day)s"> </label>
    <label> Year <input type="text" name="year"  value="%(year)s"> </label>

	<div style='color: red'>%(error)s</div>
    <br><br>
    <input type="submit">
</form>
"""

class MainPage(webapp2.RequestHandler):
	def write_form(self, error="", month="", day="", year=""):
		self.response.out.write(form % {"error": error,
										"month": es(month),
										"day": es(day),
										"year": es(year)})
		# self.response.out.write(form)

	def get(self):
		self.write_form()

	def post(self):
		#Just get user's entry
		user_month = self.request.get('month')
		user_day = self.request.get('day')
		user_year = self.request.get('year')
		#Now perform validation
		month = vm(user_month)
		day = vd(user_day)
		year = vy(user_year)

		if not (month and day and year):
			self.write_form("Not valid",
							user_month, user_day, user_year)
		else:
			self.redirect("/thanks")

class ThanksHandler(webapp2.RequestHandler):
	def get(self):
		self.response.out.write("Thanks! That's great")


app = webapp2.WSGIApplication([('/', MainPage), ('/thanks', ThanksHandler)],
                              debug=True)
