"""This file contains classes which allow to handle URLs in a transparent way
"""
import urllib
from UserList import UserList


class URL:
    """This class represents an internet URL and provides methods in order to 
        handle it in an easy way; it encapsulates the encoding of the parameters
        so clients don't need to worry about that. It also implements the 
        __str__ method which will allow to treat it as a simple string.
       
       Attributes:
        _base - (String) base url containing the protocol, hostname and path 
            in a correct way
        _params - (Dict) parameters to be added to the URL
    """
    
    def __init__( self, base, **params ):
        self._segment = ""
        self.setBase( base )
        self.setParams( params )

    def getBase( self ):
        return self._base

    def setBase( self, newBase ):
        self._base = str( newBase ).strip()

    def getSegment( self ):
        return self._segment

    def setSegment( self, newSegment ):
        self._segment = newSegment.strip()

    def setParams(self,params):
        self._params = {}
        for name in params.keys():
            self.addParam( name, params[name] )

    def addParam( self, name, value ):
        self._params[name.strip()] = value

    def delParam( self, name ):
        if self._params.has_key( name.strip() ):
            del self._params[name.strip()]

    def _encodeParamValue( self, value ): 
        return urllib.quote_plus( str( value ).strip() )

    def _getParamsURLForm( self ):
        l = []
        for name in self._params.keys():
            value = self._params[name]
            if type(value) == list or isinstance(value, UserList):
                for v in value:
                    l.append("%s=%s"%(name, self._encodeParamValue( v )))
            else:
                l.append("%s=%s"%(name, self._encodeParamValue( value )))
        return "&amp;".join( l )

    def __str__( self ):
        params = self._getParamsURLForm()
        if params.strip() != "":
            params = "?%s"%self._getParamsURLForm()
        segment = self.getSegment()
        if segment != "":
            segment = "#%s"%segment
        return "%s%s%s"%( self.getBase(), params, segment )


class MailtoURL:
    
    def __init__( self, dest, **params ):
        self._destination = dest
        self.setSubject( params.get("subject", "") )

    def setSubject( self, newSubject ):
        self._subject = newSubject.strip()

    def _encodeParamValue( self, value ):
        return urllib.quote( str( value ) )

    def _getParamsURLForm( self ):
        l = []
        l.append("subject=%s"%self._subject)
        return "&".join(l)

    def __str__( self ):
        res = "mailto:%s"%self._destination
        params = self._getParamsURLForm()
        if params != "":
            res = "%s?%s"%(res, params)
        return res

            
