# -*- coding: UTF-8 -*-
#    This file is part of arena.
#
#    arena is free software: you can redistribute it and/or modify it
#    under the terms of the GNU General Public License as published by the
#    Free Software Foundation; either version 3 of the License or, at your
#    option, any later version.
#
#    arena is distributed in the hope that it will be useful, but
#    WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABLITY
#    or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
#    License for more details.
#
#    You should have received a copy of the GNU General Public License along
#    with arena.  If not, see <http://www.gnu.org/licenses/>.

## @file
#  This file defines an application class that handles a CGI environment.

from Library.Application.Applications import AnApplication
from Library.HTTP.HTTPRequests import AnHTTPRequest
from Library.String.Utilities import String
import os.path, urllib

## An application class that handles a CGI environment.
#
#  This class should not be instantiated directly, as it does not implement
#  the run() method inherited from AnApplication.  Instead, a subclass of this
#  class should be defined; that class needs only to define the run() method
#  to do something with the information obtained by this class.
class ACGIApplication(AnApplication):
    ## Constructor
    def __init__(Self, **arguments):
        AnApplication.__init__(Self, *arguments)

    ## Initializer
    def init(Self):
        result = AnApplication.init(Self)
        if result == True:
            # Get the environment variables pertaining to the HTTP request
            Self.Request = AnHTTPRequest()
            Self.Request.get()
            # Get the cookies pertaining to the HTTP request
            Self.Cookie = None
            if Self.Request.Cookie is not None:
                Self.Cookie = Self.Request.Cookie
            # Establish private variables
            # The path to the executing script
            Self._path["client"] = \
              os.path.dirname(Self.Request.Script.name)

        return result

    ## Destructor
    def __del__(Self):
        del Self.Cookie
        del Self.Request

        AnApplication.__del__(Self)

    ## Construct a URL for the remote client which contains the path to
    #  the running script, the name of the running script, and any additional
    #  query components provided.  This allows valid links to be constructed 
    #  without the need to hard-code them.
    def url(Self, **queryComponents):
        result = Self._path["client"] + "/" + Self._script
        if len(queryComponents) > 0:
            queryString = String.implode(queryComponents, "&")
            queryString = urllib.quote_plus(queryString, "&=$/")
            queryString = queryString.replace("&", "&amp;")
            
            result += "?" + queryString

        return result
