import org.gradle.plugins.ide.idea.model.IdeaModel
import org.gradle.plugins.ide.idea.model.IdeaModule

class AndroidPlugin implements Plugin<Project> {

    @Override
    void apply(Project project) {
        if (!project.hasProperty("android")) return

        def variant = System.getProperty("androidVariant")

        project.afterEvaluate {
            def android = project.android

            IdeaModel ideaModel = (IdeaModel)project.extensions.findByName("idea")
            IdeaModule module = ideaModel.module

            android.applicationVariants.all { appVariant ->
                if (appVariant.name != variant) return

                // TODO Handle merge conflicts (e.g. debug sourceset overrides main sourceset)
                appVariant.sourceSets.forEach {
                    if(it.name == "test" || it.name == "androidTest") {
                        it.kotlinDirectories.forEach {
                            module.testSourceDirs.add(new File(it.toString()))
                        }
                    } else {
                        it.kotlinDirectories.forEach {
                            module.sourceDirs.add(new File(it.toString()))
                        }
                    }
                }

                // TODO Handle multiple module dependencies
                android.bootClasspath.each {
                    module.sourceDirs.add(new File("jar:${it.path}"))
                }
                appVariant.getCompileClasspath().files.each {
                    // This is a workaround as we cannot add new dependencies to IdeaModel because of project.afterEvaluate
                    // But we need project.afterEvaluate so appVariant.getCompileClasspath() works
                    module.sourceDirs.add(new File("jar:${it.path}"))
                }
            }
        }
    }
}

allprojects {
    afterEvaluate {
        it.getPlugins().apply("idea")
        it.getPlugins().apply(AndroidPlugin)
    }
}