# coding: UTF-8

import urllib2
import ssl
import urlparse

##!!!!##################################################################################################
#### Own written code can be placed above this commentblock . Do not change or delete commentblock! ####
########################################################################################################
##** Code created by generator - DO NOT CHANGE! **##

class WebRequest_https_10707(hsl20_4.BaseModule):

    def __init__(self, homeserver_context):
        hsl20_4.BaseModule.__init__(self, homeserver_context, "hsl20_4_fw_examples")
        self.FRAMEWORK = self._get_framework()
        self.LOGGER = self._get_logger(hsl20_4.LOGGING_NONE,())
        self.PIN_I_URL=1
        self.PIN_O_RESPONSE_DATA=1
        self.FRAMEWORK._run_in_context_thread(self.on_init)

########################################################################################################
#### Own written code can be placed after this commentblock . Do not change or delete commentblock! ####
###################################################################################################!!!##

    def on_init(self):
        pass

    def on_input_value(self, index, value):
        # NOTE:
        # This example does NOT cover exception handling or URL redirection. 
        
        # Parse the URL to substitute the host.
        url_parsed = urlparse.urlparse(value)
        # Use Framework to resolve the host ip adress. 
        host_ip = self.FRAMEWORK.resolve_dns(url_parsed.hostname)
        # Append port if provided.
        netloc = host_ip
        if(url_parsed.port!=None):
            netloc+=':%s' % url_parsed.port
        # Build URL with the host replaced by the resolved ip address.
        url_resolved = urlparse.urlunparse((url_parsed[0], netloc) + url_parsed[2:])
        # Build a SSL Context to disable certificate verification.
        ctx = ssl._create_unverified_context()
        # Build a http request and overwrite host header with the original hostname.
        request = urllib2.Request(url_resolved, headers={'Host':url_parsed.hostname})
        # Open the URL and read the response.
        response = urllib2.urlopen(request, context=ctx)
        response_data = response.read()
        # Write response to output 1.
        self._set_output_value(self.PIN_O_RESPONSE_DATA, response_data)
        