////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2015 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
////////////////////////////////////////////////////////////////////////////////
package edu.cmu.cs.vbc.prog.checkstyle.doclets;

import com.sun.javadoc.ClassDoc;
import com.sun.javadoc.RootDoc;
import com.sun.javadoc.Tag;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;

/**
 * Doclet which is used to extract Anakia input files from the
 * Javadoc of Check implementations, so the Check's docs are
 * autogenerated.
 * Attention: this is incomplete autogenerator of Check's documentation
 * from the Check's javadoc. It is not used now, and should be removed from
 * master branch till completed.
 * @author lkuehne
 */
public final class CheckDocsDoclet
{
    /** javadoc command line option for dest dir. */
    private static final String DEST_DIR_OPT = "-d";

    /** Stop instances being created. */
    private CheckDocsDoclet()
    {
    }

    /**
     * Comparator that compares the {@link ClassDoc ClassDocs} of two checks
     * by their check name.
     */
    private static class ClassDocByCheckNameComparator implements
        Comparator<ClassDoc>
    {
        /** {@inheritDoc} */
        public int compare(ClassDoc object1, ClassDoc object2)
        {
            final String checkName1 = getCheckName(object1);
            final String checkName2 = getCheckName(object2);
            return checkName1.compareTo(checkName2);
        }
    }

    /**
     * The first sentence of the check description.
     *
     * @param classDoc class doc of the check, e.g. EmptyStatement
     * @return The first sentence of the check description.
     */
    private static String getDescription(final ClassDoc classDoc)
    {
        final Tag[] tags = classDoc.firstSentenceTags();
        final StringBuffer buf = new StringBuffer();
        if (tags.length > 0) {
            buf.append(tags[0].text());
        }
        removeOpeningParagraphTag(buf);
        return buf.toString();
    }

    /**
     * Removes an opening p tag from a StringBuffer.
     * @param text the text to process
     */
    private static void removeOpeningParagraphTag(final StringBuffer text)
    {
        final String openTag = "<p>";
        final int tagLen = openTag.length();
        if ((text.length() > tagLen)
                && text.substring(0, tagLen).equals(openTag))
        {
            text.delete(0, tagLen);
        }
    }

    /**
     * Returns the official name of a check.
     *
     * @param classDoc the the check's documentation as extracted by javadoc
     * @return the check name, e.g. "IllegalImport" for
     * the "c.p.t.c.c.i.IllegalImportCheck" class.
     */
    private static String getCheckName(final ClassDoc classDoc)
    {
        final String strippedClassName = classDoc.typeName();
        final String checkName;
        if (strippedClassName.endsWith("Check")) {
            checkName = strippedClassName.substring(
                    0, strippedClassName.length() - "Check".length());
        }
        else {
            checkName = strippedClassName;
        }
        return checkName;
    }

    /**
     * Writes the opening tags of an xdoc.
     * @param printWriter you guessed it ... the target to print to :)
     * @param title the title to use for the document.
     */
    private static void writeXdocsHeader(
            final PrintWriter printWriter,
            final String title)
    {
        printWriter.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        printWriter.println("<document>");
        printWriter.println("<properties>");
        printWriter.println("<title>" + title + "</title>");
        printWriter.println("<author "
                + "email=\"checkstyle-devel@lists.sourceforge.net"
                + "\">Checkstyle Development Team</author>");
        printWriter.println("</properties>");
        printWriter.println("<body>");
        printWriter.flush();
    }

    /**
     * Writes the closing tags of an xdoc document.
     * @param printWriter you guessed it ... the target to print to :)
     */
    private static void writeXdocsFooter(final PrintWriter printWriter)
    {
        printWriter.println("</body>");
        printWriter.println("</document>");
        printWriter.flush();
    }

    /**
     * Doclet entry point.
     * @param root parsed javadoc of all java files passed to the javadoc task
     * @return true (TODO: semantics of the return value is not clear to me)
     * @throws IOException if there are problems writing output
     */
    public static boolean start(RootDoc root) throws IOException
    {
        final ClassDoc[] classDocs = root.classes();

        final File destDir = new File(getDestDir(root.options()));

        final File checksIndexFile = new File(destDir, "availablechecks.xml");
        final PrintWriter fileWriter = new PrintWriter(
                new FileWriter(checksIndexFile));
        writeXdocsHeader(fileWriter, "Available Checks");

        fileWriter.println("<p>Checkstyle provides many checks that you can"
                + " apply to your source code. Below is an alphabetical"
                + " reference, the site navigation menu provides a reference"
                + " organized by functionality.</p>");
        fileWriter.println("<table>");

        Arrays.sort(classDocs, new ClassDocByCheckNameComparator());

        for (final ClassDoc classDoc : classDocs) {

            // TODO: introduce a "CheckstyleModule" interface
            // so we can do better in the next line...
            if (classDoc.typeName().endsWith("Check")
                    && !classDoc.isAbstract())
            {
                String pageName = getPageName(classDoc);

                // allow checks to override pageName when
                // java package hierarchy is not reflected in doc structure
                final Tag[] docPageTags = classDoc.tags("checkstyle-docpage");
                if ((docPageTags != null) && (docPageTags.length > 0)) {
                    pageName = docPageTags[0].text();
                }

                final String descr = getDescription(classDoc);
                final String checkName = getCheckName(classDoc);


                fileWriter.println("<tr>"
                        + "<td><a href=\""
                        + "config_" + pageName + ".html#" + checkName
                        + "\">" + checkName + "</a></td><td>"
                        + descr
                        + "</td></tr>");
            }
        }

        fileWriter.println("</table>");
        writeXdocsFooter(fileWriter);
        fileWriter.close();
        return true;
    }

    /**
     * Calculates the human readable page name for a doc page.
     *
     * @param classDoc the doc page.
     * @return the human readable page name for the doc page.
     */
    private static String getPageName(ClassDoc classDoc)
    {
        final String packageName = classDoc.containingPackage().name();
        final String pageName =
                packageName.substring(packageName.lastIndexOf('.') + 1);
        if ("checks".equals(pageName)) {
            return "misc";
        }
        return pageName;
    }

    /**
     * Return the destination directory for this Javadoc run.
     * @param options Javadoc commandline options
     * @return the dest dir specified on the command line (or ant task)
     */
    public static String getDestDir(String[][] options)
    {
        for (final String[] opt : options) {
            if (DEST_DIR_OPT.equalsIgnoreCase(opt[0])) {
                return opt[1];
            }
        }
        return null; // TODO: throw exception here ???
    }

    /**
     * Returns option length (how many parts are in option).
     * @param option option name to process
     * @return option length (how many parts are in option).
     */
    public static int optionLength(String option)
    {
        if (DEST_DIR_OPT.equals(option)) {
            return 2;
        }
        return 0;
    }

}
