import org.apache.tools.ant.taskdefs.condition.Os

buildscript {
    repositories {
        maven { url 'https://www.myget.org/F/rd-snapshots/maven/' }
        mavenCentral()
    }

    dependencies {
        classpath("com.jetbrains.rd:rd-gen:2021.3.3")
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.31")
        classpath("org.jetbrains.kotlin:kotlin-compiler-embeddable:1.5.31")
    }
}

plugins {
    id 'java'
    id 'org.jetbrains.kotlin.jvm' version '1.5.31'
    id 'org.jetbrains.intellij' version '1.1.6'
}

ext {
    repoRoot = projectDir
    pluginVersion = '1.4.6'
    // https://www.jetbrains.com/intellij-repository/snapshots - link to repo of RD snapshots
    ProductVersion = "${productVersion}-SNAPSHOT"
    isWindows = Os.isFamily(Os.FAMILY_WINDOWS)
    rdLibDirectory = new File(repoRoot, "build/riderRD-${ProductVersion}/lib/rd")
    dotNetDir = new File(repoRoot, "src/dotnet")
    dotNetPluginId = "Xamarin.Forms.HotReload.Extension.Rider"
    dotnetSolution = new File(repoRoot, "Xamarin.Forms.HotReload.Extension.Rider.sln")
}

repositories {
    maven { url 'https://jetbrains.com/intellij-repository/snapshots' }
    maven { url 'https://cache-redirector.jetbrains.com/intellij-repository/snapshots' }
    maven { url 'https://cache-redirector.jetbrains.com/maven-central' }
    flatDir { dirs rdLibDirectory.absolutePath }
}

wrapper {
    gradleVersion = '6.9.1'
    distributionType = Wrapper.DistributionType.ALL
    distributionUrl = "https://cache-redirector.jetbrains.com/services.gradle.org/distributions/gradle-${gradleVersion}-all.zip"
}

if (!ext.has("BuildConfiguration"))
    ext.BuildConfiguration = "Release"

if (ext.has("pluginVersion"))
    ext.version = ext.pluginVersion

version ext.version

sourceSets {
    main {
        java.srcDir 'src/rider/main/kotlin'
        resources.srcDir 'src/rider/main/resources'
    }
}

compileKotlin {
    kotlinOptions { jvmTarget = "1.8" }
}

intellij {
    type = 'RD'
    patchPluginXml.untilBuild = providers.provider({ null })
    // Don't patch `untilBuild` version.
    patchPluginXml.sinceBuild = "212.0"
    //Only one of the arguments `version` or `localPath` should be passes in a time
    //localPath = 'HERE SHOULD BE PATH TO YOUR LOCAL RIDER'
    version = "${ProductVersion}"
    downloadSources = false
}

runPluginVerifier {
    ideVersions = ["RD-2021.2", "RD-2021.3"]
}

def riderSdkPackageVersion = {
    def sdkPath = new File(repoRoot, "/build/riderRD-$ProductVersion")
    def path = new File(sdkPath, "lib/ReSharperHostSdk")
    if (!path.isDirectory()) error("$path does not exist or not a directory")

    def sdkPackageName = "JetBrains.Rider.SDK"

    def regex = "${sdkPackageName}\\.([\\d\\.]+.*)\\.nupkg"
    def matchingPackage = path.list().find { it =~ regex }
    def groups = matchingPackage =~ regex
    return groups[0][1]
}

task compileDotNet {
    def riderSdkVersionPropsPath = new File(dotNetDir, "SdkVersion.props")
    def version = "2021.2.0-*"

//  ToDo: Better to use in future def version = riderSdkPackageVersion()
    riderSdkVersionPropsPath.text = ''
    riderSdkVersionPropsPath << "<Project>\n"
    riderSdkVersionPropsPath << "   <PropertyGroup>\n"
    riderSdkVersionPropsPath << "     <SdkVersion>${version}</SdkVersion>\n"
    riderSdkVersionPropsPath << "  </PropertyGroup>\n"
    riderSdkVersionPropsPath << " </Project>\n"

    doLast {
        exec {
            boolean isUnix = Os.isFamily(Os.FAMILY_UNIX)
            if (isUnix) {
                if (Os.isFamily(Os.FAMILY_MAC)) {
                    environment "FrameworkPathOverride", "/Library/Frameworks/Mono.framework/Versions/Current/lib/mono/4.5"
                } else {
                    environment "FrameworkPathOverride", "/usr/lib/mono/4.5"
                }
            }

            executable "dotnet"
            args "msbuild", "/t:Restore;Rebuild", "$dotnetSolution", "/p:Configuration=$BuildConfiguration"
            workingDir rootDir
        }
    }
}

buildPlugin {
    outputs.upToDateWhen { false }
    doLast {
        copy {
            from "$buildDir/distributions/$rootProject.name-${version}.zip"
            into "$rootDir/output"
        }

        def changelogText = file("$repoRoot/CHANGELOG.md").text
        def changelogMatches = changelogText =~ /(?s)(-.+?)(?=##|$)/
        def changeNotes = changelogMatches.collect {
            it[1].replaceAll(/(?s)- /, "\u2022 ").replaceAll(/`/, "").replaceAll(/,/, "%2C")
        }.take(1).join("")

        exec {
            executable "dotnet"
            args "msbuild", "/t:Pack", "$dotnetSolution", "/p:Configuration=$BuildConfiguration", "/p:PackageOutputPath=$rootDir/output", "/p:PackageReleaseNotes=$changeNotes", "/p:PackageVersion=$version"
        }
    }
}

apply plugin: 'com.jetbrains.rdgen'

rdgen {
    def modelDir = new File(repoRoot, "protocol/src/main/kotlin/model")
    def csOutput = new File(repoRoot, "src/dotnet/Xamarin.Forms.HotReload.Extension.Rider/Model")
    def ktOutput = new File(repoRoot, "src/rider/main/kotlin/hotreload.extension.rider/model")

    verbose = true
    classpath "$rdLibDirectory/rider-model.jar"
    sources "$modelDir/rider"
    hashFolder = 'build/rdgen/rider'
    packages = "model.rider"

    generator {
        language = "kotlin"
        transform = "asis"
        root = "com.jetbrains.rider.model.nova.ide.IdeRoot"
        namespace = "com.jetbrains.rider.model"
        directory = "$ktOutput"
    }

    generator {
        language = "csharp"
        transform = "reversed"
        root = "com.jetbrains.rider.model.nova.ide.IdeRoot"
        namespace = "JetBrains.Rider.Model"
        directory = "$csOutput"
    }
}

patchPluginXml {
    def changelogText = file("$repoRoot/CHANGELOG.md").text
    def changelogMatches = changelogText =~ /(?s)(-.+?)(?=##|$)/

    changeNotes.set(provider {
        changelogMatches.collect {
            it[1].replaceAll(/(?s)\r?\n/, "<br />\n")
        }.take(1).join('')
    })
}

tasks.register('copyDllsToSandbox', Copy) {
    def rootExtFolder = file("$projectDir/..").getAbsolutePath()

    def coreExtId = "Xamarin.Forms.HotReload.Extension"
    def coreExtOutputFolder = "$rootExtFolder/$coreExtId/bin/$BuildConfiguration/net472"
    def outputFolder = "$dotNetDir/$dotNetPluginId/bin/${dotNetPluginId}/$BuildConfiguration"
    def dllFiles = [
            "$outputFolder/${dotNetPluginId}.dll",
            "$outputFolder/${dotNetPluginId}.pdb",
            "$coreExtOutputFolder/${coreExtId}.dll",
            "$coreExtOutputFolder/${coreExtId}.pdb"
    ]

    def dstPath = "$projectDir\\build\\idea-sandbox\\plugins\\xamarin.forms.hotreload.extension.rider\\dotnet"

    dllFiles.forEach({ f ->
        from f
    })
    into dstPath

    doLast {
        dllFiles.forEach({ f ->
            def file = file(f)
            if (!file.exists()) throw new RuntimeException("File $file does not exist")
        })
    }
}

prepareSandbox {
    dependsOn compileDotNet
    dependsOn copyDllsToSandbox
}