#!/usr/bin/env python3

class FilterModule(object):
    def filters(self):
        return {
            'gsdl3servlet_domain_url': self.gsdl3servlet_domain_url
        }

    def gsdl3servlet_domain_url(self, gsdl3servlet_info):
        # print(gsdl3servlet_info)
        
        protocol = gsdl3servlet_info['protocol']
        domain   = gsdl3servlet_info['domain']

        if gsdl3servlet_info.get("port") is None:
          if (protocol == "http"):
              gsdl3servlet_info['port'] = "80"
          elif (protocol == "https"):
              gsdl3servlet_info['port'] = "443"
          else:
              raise AnsibleError("To infer default port, need 'protocol' to be specified as either \"http\" or \"https\", but encountered: %s" % protocol)
        
        port       = gsdl3servlet_info['port']
        domain_url = None
        
        if (protocol == "http"):
            if (port == "80"):
                # default for http => can skip it
                domain_url = protocol + "://" + domain
            else:
                domain_url = protocol + "://" + domain + ":" + port
        elif (protocol == "https"):
            if (port == "443"):
                # default for https => can skip it
                domain_url = protocol + "://" + domain
            else:
                domain_url = protocol + "://" + domain + ":" + port

        else:
            raise AnsibleError("Expected 'http' or 'https', but encountered protocol: %s" % protocol)
        
        return domain_url
