import os
import pywps
from pywps.Exceptions import NoApplicableCode, WPSException


def application(environ, start_response):

    os.environ['PYWPS_CFG'] = environ['PYWPS_CFG']
    os.environ['PYWPS_PROCESSES'] = environ['PYWPS_PROCESSES']

    status = '200 OK'
    response_headers = [('Content-type', 'text/xml')]
    start_response(status, response_headers)

    inputQuery = None
    if "REQUEST_METHOD" in environ and environ["REQUEST_METHOD"] == "GET":
        inputQuery = environ["QUERY_STRING"]
    elif "wsgi.input" in environ:
        inputQuery = environ['wsgi.input']

    if not inputQuery:
        err = NoApplicableCode("No query string found.")
        return [err.getResponse()]

    # create the WPS object
    try:
        wps = pywps.Pywps(environ["REQUEST_METHOD"])
        if wps.parseRequest(inputQuery):
            pywps.debug(wps.inputs)
            wps.performRequest()
            return wps.response
    except WPSException as e:
        return [e]
    except Exception as e:
        return [e]
