# Copyright (c) 2010 ActiveState Software Inc. All rights reserved.

from pypm.common.util import wrapped


class PyPMClientError(Exception): pass


class PackageNotFound(PyPMClientError):
    """No package for the given requirement is found in the repositories.

    self.requirement:  the missing requirement(s)
    self.required_by:  the requirement that required this

    If `required_by` is None, then `requirement` is an user-requested package
    (in `pypm install ...`), as opposed to that which is requested by another
    requirement (i.e., a dependency). Typically, the former is a less severe
    exception.
    """
    
    def __init__(self, requirement, required_by=None):
        self.requirement = requirement
        self.required_by = required_by
        msg =  'no such package found for requirement "%s"' % requirement
        if required_by:
            msg += '; required by "%s"' % required_by
        msg += "; try PyPM Index:  http://code.activestate.com/pypm/search:%s/" % requirement
        super(PackageNotFound, self).__init__(wrapped(msg))
        


class NoPackageInstalled(PyPMClientError):
    """No such package installed"""

    def __init__(self, name, version):
        msg = 'package "{0}{1}" is not installed'.format(
            name,
            '-'+version if version else '')
        super(NoPackageInstalled, self).__init__(wrapped(msg))



class PackageAccessError(PyPMClientError):
    """Errors related to accessing a package from ActiveState repository
    
    Eg: If a Business Edition subscription is expired, one cannot install
    the BE package.
    """
    
    def __init__(self, p, reason, msg):
        """
        - p:       The package that failed to install
        - reason:  The actual reason for the failure
        - msg:     The diagnostic message we show to the user; separated by \n
        """
        self.p = p
        self.reason = reason
        self.msg = msg
        
    def __str__(self):
        tmpl = r'''Can't install {self.p.full_name}: {self.reason}

{starred_msg}'''
        return tmpl.format(
            self=self,
            starred_msg = '*** ' + ('\n*** '.join(self.msg.splitlines())))
    
