#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2014  Alex Merry <alex.merry@kdemail.net>
# Copyright 2014  Aurélien Gâteau <agateau@kde.org>
# Copyright 2014  Alex Turbov <i.zaufi@gmail.com>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# Python 2/3 compatibility (NB: we require at least 2.7)
from __future__ import division, absolute_import, print_function, unicode_literals

import argparse
import logging
import os
import shutil
import tempfile

from kapidox import argparserutils
from kapidox import utils
from kapidox.generator import *

DEFAULT_OUTPUT_DIR = 'apidocs'


def find_all_tagfiles(args, modulename):
    module_tag_name = modulename + '.tags'

    tagfiles = search_for_tagfiles(
            suggestion = args.qtdoc_dir,
            doclink = args.qtdoc_link,
            flattenlinks = args.qtdoc_flatten_links,
            searchpaths = ['/usr/share/doc/qt5', '/usr/share/doc/qt'])

    tagfiles += search_for_tagfiles(
            suggestion = args.kdedoc_dir,
            doclink = args.kdedoc_link,
            searchpaths = ['.', '/usr/share/doc/kf5', '/usr/share/doc/kde'],
            exclude = module_tag_name)

    return tagfiles


def parse_args():
    parser = argparse.ArgumentParser(description='Generate API documentation in the KDE style')

    group = argparserutils.add_sources_group(parser)
    group.add_argument('moduledir',
            nargs='?',
            default=os.getcwd(),
            help='Location of the module to build API documentation for; it ' +
                 'should contain a README.md file and a src/ subdirectory.' +
                 'Defaults to the current folder.')
    group.add_argument('--dependency-diagram-dir',
            help='Location of framework diagram dirs; a "Dependencies" page ' +
                 'will be included in the framework documentation if provided.')

    group = argparserutils.add_output_group(parser)
    group.add_argument('-o', '--output',
            default=DEFAULT_OUTPUT_DIR,
            help='Location where the documentation will be generated. ' +
                 'Defaults to {}.'.format(DEFAULT_OUTPUT_DIR))

    argparserutils.add_qt_doc_group(parser)

    group = parser.add_argument_group('KDE documentation')
    group.add_argument('--kdedoc-dir',
            help='Location of (local) KDE documentation; this is searched ' +
                 'for tag files to create links to KDE classes.')
    group.add_argument('--kdedoc-link',
            help='Override KDE documentation location for the links in the ' +
                 'html files.  May be a path or URL.')

    argparserutils.add_paths_group(parser)
    argparserutils.add_misc_group(parser)

    args = parser.parse_args()
    argparserutils.check_common_args(args)

    if not os.path.isdir(args.moduledir):
        logging.error(args.moduledir + ' is not a directory')
        exit(2)

    return args


def main():
    utils.setup_logging()
    args = parse_args()

    modulename = os.path.basename(os.path.abspath(os.path.realpath(args.moduledir)))

    tagfiles = find_all_tagfiles(args, modulename)

    if args.dependency_diagram_dir:
        if not os.path.isdir(args.dependency_diagram_dir):
            logging.error(args.dependency_diagram_dir + ' is not a directory')
            exit(2)

        dependency_diagram = os.path.join(args.dependency_diagram_dir, modulename + '.png')
        if not os.path.isfile(dependency_diagram):
            logging.error('No file named {}.png in {}'.format(modulename, args.dependency_diagram_dir))
            exit(2)
    else:
        dependency_diagram = None

    context = Context(args,
            # Names
            modulename=modulename,
            fancyname=utils.parse_fancyname(args.moduledir),
            # KApidox files
            resourcedir='.',
            # Input
            srcdir=args.moduledir,
            tagfiles=tagfiles,
            dependency_diagram=dependency_diagram,
            # Output
            outputdir=args.output,
            )
    create_dirs(context)
    copy_dir_contents(os.path.join(context.doxdatadir, 'htmlresource'), context.htmldir)
    tmp_dir = tempfile.mkdtemp(prefix='kgenapidox-')
    try:
        generate_apidocs(context, tmp_dir)
    finally:
        if args.keep_temp_dirs:
            logging.info('Kept temp dir at {}'.format(tmp_dir))
        else:
            shutil.rmtree(tmp_dir)
    classmap = build_classmap(context.tagfile)
    postprocess(context, classmap)

    logging.info('Done')
    warn_log_path = os.path.join(args.output, WARN_LOGFILE)
    index_path = os.path.join(args.output, 'html/index.html')
    logging.info('Doxygen warnings are listed in {}'.format(warn_log_path))
    logging.info('API documentation has been generated in {}'.format(index_path))

if __name__ == "__main__":
    main()

