#!/usr/bin/env python
import os
import sys

import sh

from clint.command import Command

from debgit.changelog import get_changelog_entries, get_distribution
from debgit.version import get_version

DEFAULT_CHANGELOG_FILE = 'debian/changelog'


class CreateChangelog(Command):
    """
    debgit-create-changelog

    Generate a changelog file using debgit-get-changelog-entries.

    This command uses the `dch` tool to create a changelog file.
    """

    def __init__(self, doc=None):
        super(CreateChangelog, self).__init__(doc=doc or self.__class__.__doc__)

    def _fill_parser(self):
        """
        Add optional and positional arguments to the arg parser
        """

        super(CreateChangelog, self)._fill_parser()

        p = self.parser

        p.add_argument('package_name', nargs='?',
                       help='the name of this repository')
        p.add_argument('-c', '--changelog', default=DEFAULT_CHANGELOG_FILE,
                       help='destination file, defaults to "{0}"'.format(DEFAULT_CHANGELOG_FILE))

    def _get_package_name(self):
        """
        Return the name of the package.

        Use the name of the current directory when one is not given on the
        command line.
        """

        if self.args.package_name is None:
            package_name = os.path.basename(os.getcwd())
        else:
            package_name = self.args.package_name

        return package_name.lower()

    def create_changelog(self, path, initial_message=None):
        """
        Create the base changelog file
        """

        distribution = get_distribution()
        package_name = self._get_package_name()

        sh.dch(
           '--create', '--empty',
           '-c', path,
           '--newversion', get_version(),
           '--package', package_name,
           '--force-distribution',
           '--distribution', distribution, initial_message
        )

    def run(self):
        """
        Generate the changelog file.

        Use the `dch` command to generate a custom changelog file based on the
        commits between the current and last tags that have been marked with
        the marker "Changelog:"
        """

        changelog = self.args.changelog
        entries_iterator = get_changelog_entries()

        self.logger.debug('writing to {0}'.format(changelog))

        try:
            entry = entries_iterator.next()

            self.create_changelog(changelog, entry)

            for entry in entries_iterator:
                sh.dch('-c', changelog, entry)
        except StopIteration:
            self.create_changelog()


if __name__ == '__main__':
    command = CreateChangelog()
    try:
        sys.exit(command.run() or 0)
    except KeyboardInterrupt:
        command.quit()
