package cn.ibizlab.codegen.ignore;

import cn.ibizlab.codegen.ignore.rules.DirectoryRule;
import cn.ibizlab.codegen.ignore.rules.Rule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;


public class CodegenIgnoreProcessor {

    private static final Logger LOGGER = LoggerFactory.getLogger(CodegenIgnoreProcessor.class);

    private File ignoreFile = null;

    private List<Rule> exclusionRules = new ArrayList<>();
    private List<Rule> inclusionRules = new ArrayList<>();


    public static CodegenIgnoreProcessor getInstance(final String... baseDirectorys) {

        for(String baseDirectory:baseDirectorys)
        {
            if(StringUtils.isEmpty(baseDirectory))
                continue;
            final File directory = new File(baseDirectory);
            final File targetIgnoreFile = new File(directory, ".ibizlab-generator-ignore");
            if (directory.exists() && directory.isDirectory() && targetIgnoreFile.exists() && targetIgnoreFile.isFile()) {
                CodegenIgnoreProcessor processor = new CodegenIgnoreProcessor();
                try {
                    try (FileInputStream fileInputStream = new FileInputStream(targetIgnoreFile);
                         InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
                         BufferedReader reader = new BufferedReader(inputStreamReader)) {
                        String line;

                        // NOTE: Comments that start with a : (e.g. //:) are pulled from git documentation for .gitignore
                        // see: https://github.com/git/git/blob/90f7b16b3adc78d4bbabbd426fb69aa78c714f71/Documentation/gitignore.txt
                        while ((line = reader.readLine()) != null) {
                            if(
                                //: A blank line matches no files, so it can serve as a separator for readability.
                                    line.length() == 0
                            ) continue;

                            Rule rule = Rule.create(line);

                            // rule could be null here if it's a COMMENT, for example
                            if(rule != null) {
                                if (Boolean.TRUE.equals(rule.getNegated())) {
                                    processor.inclusionRules.add(rule);
                                } else {
                                    processor.exclusionRules.add(rule);
                                }
                            }
                        }
                    }
                    processor.ignoreFile = targetIgnoreFile;
                } catch (IOException e) {
                    LOGGER.error(String.format(Locale.ROOT, "Could not process %s.", targetIgnoreFile.getName()), e.getMessage());
                }
                return processor;
            }
        }
        LOGGER.info("Output directory ({}) does not exist, or is inaccessible. No file (.ibizlab-generator-ignore) will be evaluated.", baseDirectorys);
        return new CodegenIgnoreProcessor();
    }




    /**
     * Determines whether or not a file defined by {@code toEvaluate} is allowed,
     * under the exclusion rules from the ignore file being processed.
     *
     * @param targetFile The file to check against exclusion rules from the ignore file.
     * @return {@code false} if file matches any pattern in the ignore file (disallowed), otherwise {@code true} (allowed).
     */
    public boolean allowsFile(final File targetFile) {
        if(this.ignoreFile == null) return true;

        File file = new File(this.ignoreFile.getAbsoluteFile().getParentFile().toURI().relativize(targetFile.toURI()).getPath());
        boolean directoryExcluded = false;
        boolean exclude = false;
        if(exclusionRules.size() == 0 && inclusionRules.size() == 0) {
            return true;
        }

        // NOTE: We *must* process all exclusion rules
        for (int i = 0; i < exclusionRules.size(); i++) {
            Rule current = exclusionRules.get(i);
            Rule.Operation op = current.evaluate(file.getPath());

            switch (op){
                case EXCLUDE:
                    exclude = true;

                    // Include rule can't override rules that exclude a file by some parent directory.
                    if(current instanceof DirectoryRule) {
                        directoryExcluded = true;
                    }
                    break;
                case INCLUDE:
                    // This won't happen here.
                    break;
                case NOOP:
                    break;
                case EXCLUDE_AND_TERMINATE:
                    i = exclusionRules.size();
                    break;
            }
        }

        if(exclude) {
            // Only need to process inclusion rules if we've been excluded
            for (int i = 0; exclude && i < inclusionRules.size(); i++) {
                Rule current = inclusionRules.get(i);
                Rule.Operation op = current.evaluate(file.getPath());

                // At this point exclude=true means the file should be ignored.
                // op == INCLUDE means we have to flip that flag.
                if(op.equals(Rule.Operation.INCLUDE)) {
                    if(current instanceof DirectoryRule && directoryExcluded) {
                        // e.g
                        // baz/
                        // !foo/bar/baz/
                        // NOTE: Possibly surprising side effect:
                        // foo/bar/baz/
                        // !bar/
                        exclude = false;
                    } else if (!directoryExcluded) {
                        // e.g.
                        // **/*.log
                        // !ISSUE_1234.log
                        exclude = false;
                    }
                }
            }
        }

        return Boolean.FALSE.equals(exclude);
    }

    /**
     * Allows a consumer to manually inspect explicit "inclusion rules". That is, patterns in the ignore file which have been negated.
     *
     * @return A {@link Collections#unmodifiableList(List)} of rules which possibly negate exclusion rules in the ignore file.
     */
    public List<Rule> getInclusionRules() {
        return Collections.unmodifiableList(inclusionRules);
    }

    /**
     * Allows a consumer to manually inspect all "exclusion rules". That is, patterns in the ignore file which represent
     * files and directories to be excluded, unless explicitly overridden by {@link CodegenIgnoreProcessor#getInclusionRules()} rules.
     *
     * NOTE: Existence in this list doesn't mean a file is excluded. The rule can be overridden by {@link CodegenIgnoreProcessor#getInclusionRules()} rules.
     *
     * @return A {@link Collections#unmodifiableList(List)} of rules which define exclusions by patterns in the ignore file.
     */
    public List<Rule> getExclusionRules() {
        return Collections.unmodifiableList((exclusionRules));
    }
}
