/*
 *  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.
 */
if (gradle.startParameter.taskNames.any { it =~ /(?i)eclipse/ }) {
    allprojects {
        apply plugin: 'eclipse'

        eclipse.classpath.file.whenMerged {
            entries.removeAll { entry -> entry.path =~ '/build/' } // affects: cli-commons, cli-picocli, console, groovydoc, macro, servlet, swing, templates, xml
            entries.unique(true) { entry -> entry.path } // affects: console, groovydoc, macro, servlet, swing, templates, xml
            entries.sort(true) { entry ->
                if (entry.class.simpleName != 'SourceFolder') {
                    "${entry.kind}:${entry.path.split('/')[-1].toLowerCase()}"
                } else {
                    "${entry.kind}:${entry.path}"
                }
            }
        }

        project.tasks.eclipse.doLast {
            if (!file("${project.projectDir}/.classpath").exists()) return

            file("${project.projectDir}/.settings/org.eclipse.jdt.groovy.core.prefs").with { prefs ->
                if (!prefs.exists()) {
                    append('''\
                        eclipse.preferences.version=1
                        groovy.compiler.level=40
                        groovy.script.filters=**/*.gradle,n,**/script*.groovy,y,**/*resources/**/*.groovy,y,**/benchmarks/**/*.groovy,y
                        org.codehaus.groovy.eclipse.preferences.compiler.project=true
                        '''.stripIndent()
                    )
                }
            }

            file("${project.projectDir}/.settings/org.eclipse.core.resources.prefs").with { prefs ->
                if (!prefs.exists()) {
                    append('''\
                        eclipse.preferences.version=1
                        encoding/<project>=UTF-8
                        '''.stripIndent()
                    )
                }
            }

            file("${project.projectDir}/.settings/org.eclipse.core.runtime.prefs").with { prefs ->
                if (!prefs.exists()) {
                    append('''\
                        eclipse.preferences.version=1
                        line.separator=\\n
                        '''.stripIndent()
                    )
                }
            }

            file("${project.projectDir}/.settings/org.eclipse.jdt.ui.prefs").with { prefs ->
                if (!prefs.exists()) {
                    append('''\
                        eclipse.preferences.version=1
                        editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true
                        org.eclipse.jdt.ui.ignorelowercasenames=true
                        org.eclipse.jdt.ui.importorder=;javax;java;\\#;
                        org.eclipse.jdt.ui.ondemandthreshold=99
                        org.eclipse.jdt.ui.staticondemandthreshold=99
                        sp_cleanup.on_save_use_additional_actions=true
                        sp_cleanup.organize_imports=true
                        sp_cleanup.remove_trailing_whitespaces=true
                        sp_cleanup.remove_trailing_whitespaces_all=true
                        sp_cleanup.remove_trailing_whitespaces_ignore_empty=false
                        sp_cleanup.update_copyright_notice=true
                        '''.stripIndent()
                    )
                }
            }
        }

        // tasks for cleaning the .settings files created above

        tasks.register('cleanEclipseGdt', Delete) {
            delete "${project.projectDir}/.settings/org.eclipse.jdt.groovy.core.prefs"
        }
        cleanEclipse.dependsOn(cleanEclipseGdt)

        tasks.register('cleanEclipseJdtUI', Delete) {
            delete "${project.projectDir}/.settings/org.eclipse.jdt.ui.prefs"
        }
        cleanEclipse.dependsOn(cleanEclipseJdtUI)

        project.tasks.cleanEclipse.doLast {
            file("${project.projectDir}/.settings/org.eclipse.core.resources.prefs").delete()
            file("${project.projectDir}/.settings/org.eclipse.core.runtime.prefs").delete()
            file("${project.projectDir}/.settings/").with { if (!listFiles()) delete() }
        }
    }

    eclipse.classpath.file.whenMerged {
        entries.findAll { entry -> entry.path =~ '^build/generated/sources/antlr' }.each { entry ->
            entry.entryAttributes['ignore_optional_problems'] = 'true'
            entry.entryAttributes['optional'] = 'true'
        }
    }

    // exclude folder 'subprojects' from root project
    eclipse.project.resourceFilter {
        type = 'EXCLUDE_ALL'
        appliesTo = 'FOLDERS'
        recursive = false
        matcher {
            id = 'org.eclipse.ui.ide.multiFilter'
            arguments = '1.0-projectRelativePath-matches-true-false-subprojects'
        }
    }

    sourceSets.main.java.srcDirs += layout.buildDirectory.dir('generated/sources/antlr4')

    eclipseClasspath.dependsOn(generateGrammarSource)
}
