import sys
sys.path.append("../")

from urllib2 import urlopen, URLError, HTTPError
from constrains import constrain_checker as constrain


class url_parsing:

      def __init__(self,baseline={}):
          self.__baseline__ = baseline

          metadata_header=["http_url","http_method"]
          constrain_check = constrain.constrain_check()
          constrain_check.metadata_checks(self.__baseline__,metadata_header)

          self.url_check()


      def url_check(self):

          try:
              self.__baseline__["http_url"].replace(' ','%20')
              check_conn = urlopen(self.__baseline__["http_url"])
              code_check = check_conn.getcode()

              if not code_check == 200:
                 print("Site : " + self.__baseline__["http_url"] + " Status : NOT OK" + " Code : " + code_check)
                 sys.exit(0)

          except Exception as e:
              print("Connectivity Issues on " + self.__baseline__["http_url"] + " "+ e.message)
              sys.exit(0)

      def retreive_data(self):

          try:
              if self.__baseline__["http_method"] == "get":
                 response = urlopen(self.__baseline__["http_url"])
                 data_on_rul = response.read()
                 return data_on_rul
              else:
                 print("Http Method : " + self.__baseline__["http_method"] + " not Supported")
                 sys.exit(0)
          except Exception as e:
              print("URL Fetching Exception : " + e.message)
              sys.exit(0)
