# -*- coding: utf-8 -*-
# Cardboardlint is a cheap lint solution for pull requests.
# Copyright (C) 2011-2017 The Cardboardlint Development Team
#
# This file is part of Cardboardlint.
#
# Cardboardlint is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# Cardboardlint is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY 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/>
# --
"""Trapdoor test using doxygen to find undocumented C++ code.

This linter uses doxygen, see http://www.doxygen.org.
"""
from __future__ import print_function

import os

from cardboardlint.common import run_command, Message, Linter


__all__ = ['linter_doxygen']


DEFAULT_CONFIG = {
    # Filename filter rules
    'filefilter': ['+ *.h'],
}


DOXYGEN_CONFIG = """\
INPUT                  = {}
DOXYFILE_ENCODING      = UTF-8
PROJECT_NAME           = poor
GENERATE_HTML          = NO
GENERATE_LATEX         = NO
WARNINGS               = YES
WARN_IF_UNDOCUMENTED   = YES
WARN_IF_DOC_ERROR      = YES
WARN_FORMAT            = "~~WARN~~ $file:$line: $text"
GENERATE_AUTOGEN_DEF   = NO
"""


def run_doxygen(_config, filenames):
    """Linter using doxygen to find undocumented cpp.

    Parameters
    ----------
    config : dict
        Dictionary that contains the configuration for the linter
        Not supported
    filenames : list
        A list of filenames to check

    Returns
    -------
    messages : list
        The list of messages generated by the external linter.

    """
    command = ['doxygen', '--version']
    print('USING              : doxygen', run_command(command, verbose=False)[0].strip())

    messages = []
    if len(filenames) > 0:
        # Call doxygen in the doc subdirectory, mute output because it only confuses
        command = ['doxygen', '-']
        stdin = DOXYGEN_CONFIG.format(' '.join(filenames))
        print('STDIN              :')
        print(stdin)
        output = run_command(command, stdin=stdin)[1]

        # Parse the file doxygen_warnings
        prefix = os.getcwd() + '/'

        lines = output.split('\n')
        for line in lines:
            if line.startswith('~~WARN~~'):
                location, description = line[9:].split(None, 1)
                filename, lineno = location.split(':')[:2]
                if filename.startswith(prefix):
                    filename = filename[len(prefix):]
                message = Message(filename, int(lineno), None, description)
                messages.append(message)
    return messages


# pylint: disable=invalid-name
linter_doxygen = Linter('doxygen', run_doxygen, DEFAULT_CONFIG, language='cpp')
