#!/usr/bin/python
#
# Author: Robert Collins <robert.collins@canonical.com>
#
# Copyright 2010 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, 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, see <http://www.gnu.org/licenses/>.

"""lp-milestones -- An lptools command to work with milestones in launchpad.
https://launchpad.net/lptools/

lp-milestones help commands -- list commands
"""

import time

# Might want to make errors import lazy.
from bzrlib import errors
from launchpadlib.errors import HTTPError

from lptools.command import *

class cmd_create(LaunchpadCommand):
    """Create a milestone.
    
    lp-milestone create projectname/seriesname/milestonename
    """

    takes_args = ['milestone']

    def run(self, milestone):
        components = milestone.split('/')
        if len(components) != 3:
            raise errors.BzrCommandError("milestone (%s) too short or too long."
                % milestone)
        projectname, seriesname, milestonename = components
        # Direct access takes 50% of the time of doing traversal.
        #proj = self.launchpad.projects[projectname]
        #series = proj.getSeries(name=seriesname)
        series = self.launchpad.load(projectname + '/' + seriesname)
        milestone = series.newMilestone(name=milestonename)


class cmd_delete(LaunchpadCommand):
    """Delete a milestone.
    
    lp-milestone delete projectname/milestonename

    Note that this cannot delete a milestone with releases on it (yet). The
    server will throw a 500 error, and you may see
      File "/srv/////lib/lp/registry/model/milestone.py", line 209, in destroySelf
          "You cannot delete a milestone which has a product release "
          AssertionError: You cannot delete a milestone which has a product release associated with it.
    In the trace if you have appropriate access.
    """

    takes_args = ['milestone']

    def run(self, milestone):
        components = milestone.split('/')
        if len(components) != 2:
            raise errors.BzrCommandError("milestone (%s) too short or too long."
                % milestone)
        m = self.launchpad.load('%s/+milestone/%s' % tuple(components))
        try:
            m.delete()
        except HTTPError, e:
            if e.response.status == 404:
                pass
            elif e.response.status == 500:
                self.outf.write("Perhaps the milestone has been released?\n")
                self.outf.write("If so you can undo this in the web UI.\n")
                raise
            else:
                raise


class cmd_release(LaunchpadCommand):
    """Create a release from a milestone.
    
    lp-milestone release projectname/milestonename
    """

    takes_args = ['milestone']

    def run(self, milestone):
        components = milestone.split('/')
        if len(components) != 2:
            raise errors.BzrCommandError("milestone (%s) too short or too long."
                % milestone)
        m = self.launchpad.load('%s/+milestone/%s' % tuple(components))
        now = time.strftime('%Y-%m-%d-%X', time.gmtime())
        # note: there is a bug with how the releases are created, don't be surprised
        # if they are created 'X hours ago' where 'X' is the hour in UTC.
        m.createProductRelease(date_released=now)


class cmd_rename(LaunchpadCommand):
    """Rename a milestone.
    
    lp-milestone rename projectname/milestonename newname
    """

    takes_args = ['milestone', 'newname']

    def run(self, milestone, newname):
        components = milestone.split('/')
        if len(components) != 2:
            raise errors.BzrCommandError("milestone (%s) too short or too long."
                % milestone)
        if '/' in newname:
            raise errors.BzrCommandError(
                "milestones can only be renamed within a project.")
        m = self.launchpad.load('%s/+milestone/%s' % tuple(components))
        m.name = newname
        m.lp_save()


if __name__ == "__main__":
    main()
