#!/usr/bin/env python3
# -*- coding: utf-8 -*- vim60:fdm=marker
#
# Copyright: 2016, Maximiliano Curia <maxy@debian.org>
#
# License: ISC
#  Permission to use, copy, modify, and/or distribute this software for any
#  purpose with or without fee is hereby granted, provided that the above
#  copyright notice and this permission notice appear in all copies.
#  .
#  THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
#  REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
#  AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
#  INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
#  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
#  OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
#  PERFORMANCE OF THIS SOFTWARE.

from __future__ import print_function

import logging
import sys

from contextlib import contextmanager

from .datatypes import License


@contextmanager
def open_output_file(filename):
    if filename:
        with open(filename, 'wt', encoding='utf-8') as f:
            yield f
    else:
        yield sys.stdout


def _generate_header(copyright_, f, options):
    current_format = (
        'https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/'
    )
    if options.mode == 'partial':
        paragraph = (
            'Format: {}\n'
            'Comment: *** only: {} ***'.format(
                current_format, ', '.join(options.files)))
    elif copyright_:
        header = copyright_.header
        header.format = current_format
        paragraph = header.dump().rstrip('\n')
    else:
        paragraph = 'Format: {}'.format(current_format)
    print(paragraph, file=f)
    print(file=f)
    if options.output:
        logging.debug('Generated header:\n%s', paragraph)


def generate_output(groups, filetree, copyright_, options):

    # Track the licenses that are in use
    licenses = set()

    with open_output_file(options.output) as f:
        # Print header
        _generate_header(copyright_, f, options)

        # Avoid printing 'Files: *' when working in partial mode
        if options.mode == 'partial':
            for item in options.files:
                if not filetree[item].parent:
                    continue
                filetree[item].parent.tally()

        # Print files paragraphs
        for _, group in sorted(
                groups.items(), key=lambda i: i[1].sort_key(options)):

            if not group.copyright_block_valid():
                continue

            licenses.update(group.licenses.keys())

            paragraph = group.copyright_block(options.glob)

            print(paragraph, file=f)
            print(file=f)

            if options.output:
                logging.debug('Generated group:\n%s', paragraph)

        # Print license paragraphs
        for key in sorted(licenses):
            license_ = License.get(key)
            paragraph = str(license_)

            print(paragraph, file=f)
            print(file=f)

            if options.output:
                logging.debug('Generated license block:\n%s', paragraph)
