/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.apache.rat.anttasks;

import org.apache.commons.cli.Option;
import org.apache.commons.lang3.StringUtils;
import org.apache.rat.commandline.Arg;
import org.apache.rat.DeprecationReporter;
import org.apache.rat.utils.CasedString;
import org.apache.rat.utils.DefaultLog;
import org.apache.rat.utils.Log;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.Resource;
import org.apache.tools.ant.types.resources.FileResource;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
/**
 * Generated class to provide Ant support for standard RAT command line options.
 *
 * DO NOT EDIT - GENERATED FILE
 */
public abstract class BaseAntTask extends Task {

    private static final Map<String, String> xlateName = new HashMap<>();

    private static final List<String> unsupportedArgs = new ArrayList<>();

    private static final Map<String, String> deprecatedArgs = new HashMap<>();

    static {
        xlateName.put("addLicense", "add-license");
        unsupportedArgs.add("a");
        unsupportedArgs.add("input-include-file");
        unsupportedArgs.add("input-source");
        unsupportedArgs.add("input-exclude-file");
        unsupportedArgs.add("log-level");
        unsupportedArgs.add("license-families-approved-file");
        unsupportedArgs.add("input-exclude-std");
        unsupportedArgs.add("help");
        unsupportedArgs.add("dir");
        unsupportedArgs.add("license-families-denied-file");
        unsupportedArgs.add("licenses-denied-file");
        unsupportedArgs.add("licenses-approved-file");
        unsupportedArgs.add("input-include-std");
        deprecatedArgs.put("copyright", "Use of deprecated option 'copyright'. Deprecated for removal since 0.17: Use editCopyright attribute instead.");
        deprecatedArgs.put("force", "Use of deprecated option 'force'. Deprecated for removal since 0.17: Use editOverwrite attribute instead.");
        deprecatedArgs.put("addLicense", "Use of deprecated option 'addLicense'. Deprecated for removal since 0.17: Use editLicense attribute instead.");
        deprecatedArgs.put("licenses", "Use of deprecated option 'licenses'. Deprecated for removal since 0.17: Use <config> instead.");
        deprecatedArgs.put("no-default-licenses", "Use of deprecated option 'noDefaultLicenses'. Deprecated for removal since 0.17: Use configurationNoDefaults attribute instead.");
        deprecatedArgs.put("exclude", "Use of deprecated option 'exclude'. Deprecated for removal since 0.17: Use <inputExclude> instead.");
        deprecatedArgs.put("exclude-file", "Use of deprecated option 'excludeFile'. Deprecated for removal since 0.17: Use inputExcludeFile attribute instead.");
        deprecatedArgs.put("include", "Use of deprecated option 'include'. Deprecated for removal since 0.17: Use <inputInclude> instead.");
        deprecatedArgs.put("includes-file", "Use of deprecated option 'includesFile'. Deprecated for removal since 0.17: Use inputIncludeFile attribute instead.");
        deprecatedArgs.put("scan-hidden-directories", "Use of deprecated option 'scanHiddenDirectories'. Deprecated for removal since 0.17: Use <inputIncludeStd> with 'HIDDEN_DIR' argument instead.");
        deprecatedArgs.put("stylesheet", "Use of deprecated option 'stylesheet'. Deprecated for removal since 0.17: Use outputStyle attribute instead.");
        deprecatedArgs.put("xml", "Use of deprecated option 'xml'. Deprecated for removal since 0.17: Use outputStyle attribute with the 'xml' argument instead.");
        deprecatedArgs.put("list-licenses", "Use of deprecated option 'listLicenses'. Deprecated for removal since 0.17: Use outputLicenses attribute instead.");
        deprecatedArgs.put("list-families", "Use of deprecated option 'listFamilies'. Deprecated for removal since 0.17: Use outputFamilies attribute instead.");
        deprecatedArgs.put("out", "Use of deprecated option 'out'. Deprecated for removal since 0.17: Use outputFile attribute instead.");
    }

    public static String createName(String longOpt) {
        String name = StringUtils.defaultIfEmpty(xlateName.get(longOpt), longOpt).toLowerCase(Locale.ROOT);
        return new CasedString(CasedString.StringCase.KEBAB, name).toCase(CasedString.StringCase.CAMEL);
    }

    public static List<String> unsupportedArgs() {
        return Collections.unmodifiableList(unsupportedArgs);
    }

    ///////////////////////// Start common Arg manipulation code

    /**
     * Sets the deprecation report method.
     */
    private static void setDeprecationReporter() {
        DeprecationReporter.setLogReporter(opt -> {
            String msg = deprecatedArgs.get(argsKey(opt));
            if (msg == null) {
                DeprecationReporter.getDefault().accept(opt);
            } else {
                DefaultLog.getInstance().warn(msg);
            }
        });
    }

    private static String argsKey(Option opt) {
        return StringUtils.defaultIfEmpty(opt.getLongOpt(), opt.getKey());
    }

    /**
     * A map of CLI-based arguments to values.
     */
    protected final Map<String, List<String>> args = new HashMap<>();

    /**
     * Gets the list of arguments prepared for the CLI code to parse.
     * @return the List of arguments for the CLI command line.
     */
    protected List<String> args() {
        List<String> result = new ArrayList<>();
        for (Map.Entry<String, List<String>> entry : args.entrySet()) {
            result.add("--" + entry.getKey());
            result.addAll(entry.getValue().stream().filter(Objects::nonNull).collect(Collectors.toList()));
        }
        return result;
    }

    private boolean validateSet(String key) {
        Arg arg = Arg.findArg(key);
        if (arg != null) {
            Option opt = arg.find(key);
            Option main = arg.option();
            if (opt.isDeprecated()) {
                args.remove(argsKey(main));
                // deprecated options must be explicitly set so let it go.
                return true;
            }
            // non-deprecated options may have default so ignore it if another option has already been set.
            for (Option o : arg.group().getOptions()) {
                if (!o.equals(main)) {
                    if (args.containsKey(argsKey(o))) {
                        return false;
                    }
                }
            }
            return true;
        }
        return false;
    }

    /**
     * Set a key and value into the argument list.
     * Replaces any existing value.
     * @param key the key for the map.
     * @param value the value to set.
     */
    protected void setArg(String key, String value) {
        if (value == null || StringUtils.isNotBlank(value)) {
            if (validateSet(key)) {
                List<String> values = new ArrayList<>();
                if (DefaultLog.getInstance().isEnabled(Log.Level.DEBUG)) {
                    DefaultLog.getInstance().debug(String.format("Setting %s to '%s'", key, value));
                }
                values.add(value);
                args.put(key, values);
            }
        }
    }

    /**
     * Get the list of values for a key.
     * @param key the key for the map.
     * @return the list of values for the key or {@code null} if not set.
     */
    public List<String> getArg(String key) {
        return args.get(key);
    }

    /**
     * Add values to the key in the argument list.
     * empty values are ignored. If no non-empty values are present no change is made.
     * If the key does not exist, adds it.
     * @param key the key for the map.
     * @param value the array of values to set.
     */
    protected void addArg(String key, String[] value) {
        List<String> newValues = Arrays.stream(value).filter(StringUtils::isNotBlank).collect(Collectors.toList());
        if (!newValues.isEmpty()) {
            if (validateSet(key)) {
                if (DefaultLog.getInstance().isEnabled(Log.Level.DEBUG)) {
                    DefaultLog.getInstance().debug(String.format("Adding [%s] to %s", String.join(", ", Arrays.asList(value)), key));
                }
                List<String> values = args.computeIfAbsent(key, k -> new ArrayList<>());
                values.addAll(newValues);
            }
        }
    }

    /**
     * Add a value to the key in the argument list.
     * If the key does not exist, adds it.
     * @param key the key for the map.
     * @param value the value to set.
     */
    protected void addArg(String key, String value) {
        if (StringUtils.isNotBlank(value)) {
            if (validateSet(key)) {
                List<String> values = args.get(key);
                if (DefaultLog.getInstance().isEnabled(Log.Level.DEBUG)) {
                    DefaultLog.getInstance().debug(String.format("Adding [%s] to %s", String.join(", ", Arrays.asList(value)), key));
                }
                if (values == null) {
                    values = new ArrayList<>();
                    args.put(key, values);
                }
                values.add(value);
            }
        }
    }

    /**
     * Remove a key from the argument list.
     * @param key the key to remove from the map.
     */
    protected void removeArg(String key) {
        args.remove(key);
    }

 ///////////////////////// End common Arg manipulation code

    protected BaseAntTask() {
        setDeprecationReporter();
    }

    /*  GENERATED METHODS */

    /**
     * The copyright message to use in the license headers.
     * @param copyright Copyright message to use in the license headers.
     * @deprecated Deprecated for removal since 0.17: Use editCopyright attribute instead.
     */
    public void setCopyright(String copyright) {
        setArg("copyright", copyright);

    }

    /**
     * The copyright message to use in the license headers. Usually in the form of &quot;Copyright 2008 Foo&quot;.  Only valid with editLicense attribute
     * @param editCopyright Copyright message to use in the license headers.
     */
    public void setEditCopyright(String editCopyright) {
        setArg("edit-copyright", editCopyright);

    }

    /**
     * Forces any changes in files to be written directly to the source files so that new files are not created.
     * @param force The state
     * @deprecated Deprecated for removal since 0.17: Use editOverwrite attribute instead.
     */
    public void setForce(boolean force) {
        if (force) { setArg("force", null); } else { removeArg("force"); }
    }

    /**
     * Forces any changes in files to be written directly to the source files so that new files are not created. Only valid with editLicense attribute.
     * @param editOverwrite The state
     */
    public void setEditOverwrite(boolean editOverwrite) {
        if (editOverwrite) { setArg("edit-overwrite", null); } else { removeArg("edit-overwrite"); }
    }

    /**
     * Add the Apache-2.0 license header to any file with an unknown license that is not in the exclusion list.
     * @param addLicense The state
     * @deprecated Deprecated for removal since 0.17: Use editLicense attribute instead.
     */
    public void setAddLicense(boolean addLicense) {
        if (addLicense) { setArg("addLicense", null); } else { removeArg("addLicense"); }
    }

    /**
     * Add the Apache-2.0 license header to any file with an unknown license that is not in the exclusion list. By default new files will be created with the license header, to force the modification of existing files use the editOverwrite attribute option.
     * @param editLicense The state
     */
    public void setEditLicense(boolean editLicense) {
        if (editLicense) { setArg("edit-license", null); } else { removeArg("edit-license"); }
    }

    /**
     * Ignore default configuration.
     * @param configurationNoDefaults The state
     */
    public void setConfigurationNoDefaults(boolean configurationNoDefaults) {
        if (configurationNoDefaults) { setArg("configuration-no-defaults", null); } else { removeArg("configuration-no-defaults"); }
    }

    /**
     * Ignore default configuration.
     * @param noDefaultLicenses The state
     * @deprecated Deprecated for removal since 0.17: Use configurationNoDefaults attribute instead.
     */
    public void setNoDefaultLicenses(boolean noDefaultLicenses) {
        if (noDefaultLicenses) { setArg("no-default-licenses", null); } else { removeArg("no-default-licenses"); }
    }

    /**
     * Reads &lt;Expression&gt; entries from a file. Entries will be excluded from processing. Argument should be a File. (See Argument Types for clarification)
     * @param excludeFile &lt;Expression&gt; entries from a file.
     * @deprecated Deprecated for removal since 0.17: Use inputExcludeFile attribute instead.
     */
    public void setExcludeFile(String excludeFile) {
        setArg("exclude-file", excludeFile);

    }

    /**
     * Excludes files with sizes less than the number of bytes specified. Argument should be a Integer. (See Argument Types for clarification)
     * @param inputExcludeSize Files with sizes less than the number of bytes specified.
     */
    public void setInputExcludeSize(String inputExcludeSize) {
        setArg("input-exclude-size", inputExcludeSize);

    }

    /**
     * Reads &lt;Expression&gt; entries from a file. Entries will be excluded from processing. Argument should be a File. (See Argument Types for clarification)
     * @param includesFile &lt;Expression&gt; entries from a file.
     * @deprecated Deprecated for removal since 0.17: Use inputIncludeFile attribute instead.
     */
    public void setIncludesFile(String includesFile) {
        setArg("includes-file", includesFile);

    }

    /**
     * Scans hidden directories.
     * @param scanHiddenDirectories The state
     * @deprecated Deprecated for removal since 0.17: Use &lt;inputIncludeStd&gt; with 'HIDDEN_DIR' argument instead.
     */
    public void setScanHiddenDirectories(boolean scanHiddenDirectories) {
        if (scanHiddenDirectories) { setArg("scan-hidden-directories", null); } else { removeArg("scan-hidden-directories"); }
    }

    /**
     * XSLT stylesheet to use when creating the report. Either an external xsl file may be specified or one of the internal named sheets. Argument should be a StyleSheet. (See Argument Types for clarification)
     * @param outputStyle Stylesheet to use when creating the report.
     */
    public void setOutputStyle(String outputStyle) {
        setArg("output-style", outputStyle);

    }

    /**
     * XSLT stylesheet to use when creating the report. Argument should be a StyleSheet. (See Argument Types for clarification)
     * @param stylesheet Stylesheet to use when creating the report.
     * @deprecated Deprecated for removal since 0.17: Use outputStyle attribute instead.
     */
    public void setStylesheet(String stylesheet) {
        setArg("stylesheet", stylesheet);

    }

    /**
     * forces XML output rather than the textual report.
     * @param xml The state
     * @deprecated Deprecated for removal since 0.17: Use outputStyle attribute with the 'xml' argument instead.
     */
    public void setXml(boolean xml) {
        if (xml) { setArg("xml", null); } else { removeArg("xml"); }
    }

    /**
     * List the defined licenses. Argument should be a LicenseFilter. (See Argument Types for clarification)
     * @param outputLicenses The defined licenses.
     */
    public void setOutputLicenses(String outputLicenses) {
        setArg("output-licenses", outputLicenses);

    }

    /**
     * List the defined licenses. Argument should be a LicenseFilter. (See Argument Types for clarification)
     * @param listLicenses The defined licenses.
     * @deprecated Deprecated for removal since 0.17: Use outputLicenses attribute instead.
     */
    public void setListLicenses(String listLicenses) {
        setArg("list-licenses", listLicenses);

    }

    /**
     * List the defined license families. Argument should be a LicenseFilter. (See Argument Types for clarification)
     * @param outputFamilies The defined license families.
     */
    public void setOutputFamilies(String outputFamilies) {
        setArg("output-families", outputFamilies);

    }

    /**
     * List the defined license families. Argument should be a LicenseFilter. (See Argument Types for clarification)
     * @param listFamilies The defined license families.
     * @deprecated Deprecated for removal since 0.17: Use outputFamilies attribute instead.
     */
    public void setListFamilies(String listFamilies) {
        setArg("list-families", listFamilies);

    }

    /**
     * If set do not update the files but generate the reports.
     * @param dryRun The state
     */
    public void setDryRun(boolean dryRun) {
        if (dryRun) { setArg("dry-run", null); } else { removeArg("dry-run"); }
    }

    /**
     * Define the output file where to write a report to. Argument should be a File. (See Argument Types for clarification)
     * @param out The output file where to write a report to.
     * @deprecated Deprecated for removal since 0.17: Use outputFile attribute instead.
     */
    public void setOut(String out) {
        setArg("out", out);

    }

    /**
     * Define the output file where to write a report to. Argument should be a File. (See Argument Types for clarification)
     * @param outputFile The output file where to write a report to.
     */
    public void setOutputFile(String outputFile) {
        setArg("output-file", outputFile);

    }

    /**
     * Specifies the level of detail in ARCHIVE file reporting. Argument should be a ProcessingType. (See Argument Types for clarification)
     * @param outputArchive The level of detail in ARCHIVE file reporting.
     */
    public void setOutputArchive(String outputArchive) {
        setArg("output-archive", outputArchive);

    }

    /**
     * Specifies the level of detail in STANDARD file reporting. Argument should be a ProcessingType. (See Argument Types for clarification)
     * @param outputStandard The level of detail in STANDARD file reporting.
     */
    public void setOutputStandard(String outputStandard) {
        setArg("output-standard", outputStandard);

    }

    /**
     * Print information about registered licenses.
     * @param helpLicenses The state
     */
    public void setHelpLicenses(boolean helpLicenses) {
        if (helpLicenses) { setArg("help-licenses", null); } else { removeArg("help-licenses"); }
    }



    /*  GENERATED CLASSES */

    /**
     * File names for system configuration.
     */
    public Config createConfig() {
        return new Config();
    }

    public class Config {
        Config() { }

        public void addConfiguredFileset(FileSet fileSet) {
            for (Resource resource : fileSet) {
                if (resource.isFilesystemOnly()) {
                    addArg("config", ((FileResource) resource).getFile().getAbsolutePath());
                }
            }
        }

    }
    /**
     * File names for system configuration.
     * @deprecated Deprecated for removal since 0.17: Use &lt;config&gt; instead.
     */
    public Licenses createLicenses() {
        return new Licenses();
    }

    public class Licenses {
        Licenses() { }

        public void addConfiguredFileset(FileSet fileSet) {
            for (Resource resource : fileSet) {
                if (resource.isFilesystemOnly()) {
                    addArg("licenses", ((FileResource) resource).getFile().getAbsolutePath());
                }
            }
        }

    }
    /**
     * A comma separated list of approved License IDs. These licenses will be added to the list of approved licenses.
     */
    public LicensesApproved createLicensesApproved() {
        return new LicensesApproved();
    }

    public class LicensesApproved {
        LicensesApproved() { }

        public void addConfiguredLst(Lst licenseID) {
            addArg("licenses-approved", licenseID.value);
        }

        public void addConfiguredFileset(FileSet fileSet) {
            for (Resource resource : fileSet) {
                if (resource.isFilesystemOnly()) {
                    addArg("licenses-approved-file", ((FileResource) resource).getFile().getAbsolutePath());
                }
            }
        }

    }
    /**
     * A comma separated list of approved license family IDs. These license families will be added to the list of approved license families.
     */
    public LicenseFamiliesApproved createLicenseFamiliesApproved() {
        return new LicenseFamiliesApproved();
    }

    public class LicenseFamiliesApproved {
        LicenseFamiliesApproved() { }

        public void addConfiguredFileset(FileSet fileSet) {
            for (Resource resource : fileSet) {
                if (resource.isFilesystemOnly()) {
                    addArg("license-families-approved-file", ((FileResource) resource).getFile().getAbsolutePath());
                }
            }
        }

        public void addConfiguredLst(Lst familyID) {
            addArg("license-families-approved", familyID.value);
        }

    }
    /**
     * A comma separated list of denied License IDs. These licenses will be removed from the list of approved licenses. Once licenses are removed they can not be added back.
     */
    public LicensesDenied createLicensesDenied() {
        return new LicensesDenied();
    }

    public class LicensesDenied {
        LicensesDenied() { }

        public void addConfiguredFileset(FileSet fileSet) {
            for (Resource resource : fileSet) {
                if (resource.isFilesystemOnly()) {
                    addArg("licenses-denied-file", ((FileResource) resource).getFile().getAbsolutePath());
                }
            }
        }

        public void addConfiguredLst(Lst licenseID) {
            addArg("licenses-denied", licenseID.value);
        }

    }
    /**
     * A comma separated list of denied License family IDs. These license families will be removed from the list of approved licenses. Once license families are removed they can not be added back.
     */
    public LicenseFamiliesDenied createLicenseFamiliesDenied() {
        return new LicenseFamiliesDenied();
    }

    public class LicenseFamiliesDenied {
        LicenseFamiliesDenied() { }

        public void addConfiguredLst(Lst familyID) {
            addArg("license-families-denied", familyID.value);
        }

        public void addConfiguredFileset(FileSet fileSet) {
            for (Resource resource : fileSet) {
                if (resource.isFilesystemOnly()) {
                    addArg("license-families-denied-file", ((FileResource) resource).getFile().getAbsolutePath());
                }
            }
        }

    }
    /**
     * The acceptable maximum number for the specified counter. A value of '-1' specifies an unlimited number.
     */
    public CounterMax createCounterMax() {
        return new CounterMax();
    }

    public class CounterMax {
        CounterMax() { }

        public void addConfiguredCntr(Cntr counterPattern) {
            addArg("counter-max", counterPattern.value);
        }

    }
    /**
     * The minimum number for the specified counter.
     */
    public CounterMin createCounterMin() {
        return new CounterMin();
    }

    public class CounterMin {
        CounterMin() { }

        public void addConfiguredCntr(Cntr counterPattern) {
            addArg("counter-min", counterPattern.value);
        }

    }
    /**
     * Excludes files matching &lt;Expression&gt;.
     * @deprecated Deprecated for removal since 0.17: Use &lt;inputExclude&gt; instead.
     */
    public Exclude createExclude() {
        return new Exclude();
    }

    public class Exclude {
        Exclude() { }

        public void addConfiguredExpr(Expr expression) {
            addArg("exclude", expression.value);
        }

    }
    /**
     * Excludes files matching &lt;Expression&gt;.
     */
    public InputExclude createInputExclude() {
        return new InputExclude();
    }

    public class InputExclude {
        InputExclude() { }

        public void addConfiguredStd(Std standardCollection) {
            addArg("input-exclude-std", standardCollection.value);
        }

        public void addConfiguredExpr(Expr expression) {
            addArg("input-exclude", expression.value);
        }

        public void addConfiguredFileset(FileSet fileSet) {
            for (Resource resource : fileSet) {
                if (resource.isFilesystemOnly()) {
                    addArg("input-exclude-file", ((FileResource) resource).getFile().getAbsolutePath());
                }
            }
        }

    }
    /**
     * Includes files matching &lt;Expression&gt;. Will override excluded files.
     */
    public InputInclude createInputInclude() {
        return new InputInclude();
    }

    public class InputInclude {
        InputInclude() { }

        public void addConfiguredFileset(FileSet fileSet) {
            for (Resource resource : fileSet) {
                if (resource.isFilesystemOnly()) {
                    addArg("input-include-file", ((FileResource) resource).getFile().getAbsolutePath());
                }
            }
        }

        public void addConfiguredExpr(Expr expression) {
            addArg("input-include", expression.value);
        }

        public void addConfiguredStd(Std standardCollection) {
            addArg("input-include-std", standardCollection.value);
        }

    }
    /**
     * Includes files matching &lt;Expression&gt;. Will override excluded files.
     * @deprecated Deprecated for removal since 0.17: Use &lt;inputInclude&gt; instead.
     */
    public Include createInclude() {
        return new Include();
    }

    public class Include {
        Include() { }

        public void addConfiguredExpr(Expr expression) {
            addArg("include", expression.value);
        }

    }
    /**
     * Parse SCM based exclusion files to exclude specified files and directories. This action can apply to any standard collection that implements a file processor.
     */
    public InputExcludeParsedScm createInputExcludeParsedScm() {
        return new InputExcludeParsedScm();
    }

    public class InputExcludeParsedScm {
        InputExcludeParsedScm() { }

        public void addConfiguredStd(Std standardCollection) {
            addArg("input-exclude-parsed-scm", standardCollection.value);
        }

    }

    /* TYPE CLASSES */

    protected static class TxtValue {
        protected TxtValue() { }

        public String value;

        public void addText(String text) {
            value = text.trim();
        }
    }

    public static class Std extends TxtValue {
        public Std() { }
    }

    public static class Expr extends TxtValue {
        public Expr() { }
    }

    public static class Cntr extends TxtValue {
        public Cntr() { }
    }

    public static class Filename extends TxtValue {
        public Filename() { }
    }

    public static class Lst extends TxtValue {
        public Lst() { }
    }
}
