import os
import traceback

# Serves as kind of a main program
class HTML_Page:
  def __init__(self, environ):
    self.environ = environ

    pageType = environ['PATH_INFO']
    
    if pageType == '/index.html':
      self.head = self.get_index_head()
      self.body = self.get_index_body()

    elif pageType == '/add_data.html':
      error = self.parse_query_string()
      self.head = self.get_add_data_head()
      if error:
        self.body = self.get_error_body()
      else:
        self.body = self.get_add_data_body()
        self.add_data()

    elif pageType == '/report.html':
      self.head = self.get_report_head()
      self.body = self.get_report_body()
      
    else:
      self.head = ""
      self.body="<p>bad url</p>"

      
  def get_index_head(self):
    return "<head></head> \n"

  def get_index_body(self):
    return  """
              <body>
              <form name="input" action="add_data.html" method="get">
              <label>Steps<input type="number" name="steps" min="0" pattern="[0-9]+"></label>
              <label>Time<input type="number" name="hour" pattern="[0-9]+"
                      placeholder="hour">
                          <input type="number" name="minute" pattern="[0-9]+"
                          placeholder="minute">
              </label>
              <br><br>
              <input type="submit" value="Submit">
              </body>
               """

               
  def get_add_data_head(self):
    return "<head></head> \n"

  def get_add_data_body(self):
    return     """
                  <body>
                  <p>Value Added</p> 
                   <a href="index.html">Return</a> 
                   <a href="report.html">View Numbers</a>
                   </body>
                   """

  def get_error_body(self):
    return     """
                  <body>
                  <p>Error</p>
                  <p> Hour should be an integer between 0 and 24</p>
                   <a href="index.html">Return</a> 
                   </body>
                   """

  def get_report_head(self):
    return "<head></head> \n"

  def get_report_body(self):
  
    theReportBody ="<body><ul>"
    
    try:
      script_path = os.path.dirname(os.path.realpath(__file__))
      f = open(script_path+"/steps.csv", "rU")
      for line in f:
        theReportBody +="<li>"+line+"</li>"
      f.close() 
    except Exception:
      theReportBody +=traceback.format_exc()
      
    theReportBody += "</ul><a href=\"index.html\">Return</a></body>"
    return theReportBody

  def parse_query_string(self):

    # build dictionary to contain query keys and values
    self.query_value = {}
    query_param_list = self.environ['QUERY_STRING'].split('&')
    for value in query_param_list:
      value = value.split("=")
      self.query_value[value[0]] = value[1]
      
    # check hour value
    error = False  # Boolean variable
    try:
      hour = int(self.query_value["hour"]) # might crash if not in try
    except:
      error = True
    # does not try to evaluate hour if error is True, so won't crash
    if error or hour < 0 or hour > 24:  
      error = True

    return error


  def add_data(self):

    try:
      script_path = os.path.dirname(os.path.realpath(__file__))
      f = open(script_path+"/steps.csv", "a")
      f.write(self.query_value["steps"]+"\n")
      f.close()
    except Exception:
      self.body = traceback.format_exc()
      # tell user where it would have crashed
      # on Web page

  

  
  def returnHTML(self):
    theHTML =     """
                        <!doctype html> \n
                        <html> \n
                        """+self.head+self.body+"""
                         </html>
                         """
    return theHTML
