# Copyright (C) 2009 Canonical Ltd
#
# This program 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 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY 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 this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA


from urlparse import urlsplit, urlunsplit

from bzrlib import errors
from bzrlib.plugins.launchpad import cmd_launchpad_open
from bzrlib.plugins.launchpad.lp_registration import (
    LaunchpadService,
    NotLaunchpadBranch,
    )


class HostedUrlResolver(object):

    def __init__(self):
        self._lp_service = LaunchpadService()
        self._lp_open_cmd = cmd_launchpad_open()

    def get_branch_url(self, location='.'):
        """Get the web branch URL for a given location.

        @return: the URL as a string or None if none.
        """
        # TODO: generalise this to support sites other than Launchpad, e.g.
        # Savannah and/or Loggerhead on an Intranet server.
        try:
            # Note: this only checks the public location and the push location.
            # I think it ought to check the bound and parent locations as well.
            # See https://bugs.launchpad.net/bzr/+bug/488057.
            return self._lp_open_cmd._get_web_url(self._lp_service, location)
        except NotLaunchpadBranch:
            return None
        except errors.SocketConnectionError:    # workaround for bug #925951
            return None

    def get_project_url(self, location='.'):
        """Get the web project URL for a given location.

        @return: the URL as a string or None if none.
        """
        # TODO: generalise this to support sites other than Launchpad, e.g.
        # Savannah and/or Loggerhead on an Intranet server.
        try:
            branch_url = self._lp_open_cmd._get_web_url(self._lp_service, location)
        except NotLaunchpadBranch:
            return None
        except errors.SocketConnectionError:    # workaround for bug #925951
            return None

        # We found an lp branch. The format ought to be
        # https://code.xxx/~user-id/project-name/branch-name/.
        # We map that to https://xxx/project-name if we can.
        scheme, hostinfo, path = urlsplit(branch_url)[:3]
        if hostinfo.startswith('code.'):
            hostinfo = hostinfo[5:]
        parts = path.strip('/').split('/')
        if len(parts) <= 2:
            return None
        project = parts[1]
        return urlunsplit((scheme, hostinfo, project, '', ''))
