#!/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.

# Local modules
from .tree import RootInfo, DirInfo
from .dep5 import Copyright, Group
from .output import generate_output
from .cmdoptions import process_options


def prepare_output_groups(filetree, copyright_, options):

    copyright_.remove_misplaced_files(options)
    groups = copyright_.get_group_dict(options)

    for fileinfo in filetree:
        if options.mode == 'partial' and not fileinfo.included:
            continue

        # if fileinfo.group is set, it means that the parsed group matches the
        # stored group and there's no need to update it
        if fileinfo.group:
            continue
        if isinstance(fileinfo, DirInfo):
            continue

        # If we reach this it means the file needs to be added to a group.
        # TODO: for diff mode
        file_key = fileinfo.get_group_key(options)
        group = groups.setdefault(file_key, Group(file_key))
        group.add_file(fileinfo)
        fileinfo.group = group

    return groups


def main():

    options = process_options()

    filetree = RootInfo.build(options)
    copyright_ = Copyright.build(filetree, options)

    copyright_.process(filetree)
    filetree.process(options)

    groups = prepare_output_groups(filetree, copyright_, options)

    generate_output(groups, filetree, copyright_, options)

    return 0
