import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar

import java.text.SimpleDateFormat

buildscript {
    repositories {
        jcenter()

        maven {
            url "https://plugins.gradle.org/m2/"
        }
    }
}

plugins {
    id 'kotlin-multiplatform' version '1.3.31'
    id 'kotlinx-serialization' version '1.3.31'
    id "org.kravemir.gradle.sass" version "1.2.2"
    id "com.github.johnrengelman.shadow" version "5.0.0"
}

group "de.kif"
version "0.1.0"

repositories {
    mavenCentral()
    jcenter()
    maven { url 'https://jitpack.io' }
    maven { url "https://dl.bintray.com/kotlin/ktor" }
    maven { url "https://dl.bintray.com/jetbrains/markdown" }
    maven { url "https://kotlin.bintray.com/kotlinx" }
    maven { url "https://kotlin.bintray.com/kotlin-js-wrappers" }
    maven { url "https://dl.bintray.com/soywiz/soywiz" }
}
def ktor_version = '1.1.5'
def serialization_version = '0.11.0'
def observable_version = '0.9.3'
def klockVersion = "1.4.0"

kotlin {
    jvm() {
        compilations.all {
            kotlinOptions {
                jvmTarget = "1.8"
                freeCompilerArgs += [
                        "-Xuse-experimental=io.ktor.util.KtorExperimentalAPI"
                ]
            }
        }
    }
    js() {
        compilations.all {
            kotlinOptions {
                moduleKind = "umd"
                sourceMap = true
                metaInfo = true
            }
        }
    }
    sourceSets {
        commonMain {
            dependencies {
                implementation kotlin('stdlib-common')
                implementation "de.westermann:KObserve-metadata:$observable_version"
                implementation "com.soywiz:klock-metadata:$klockVersion"
                implementation "com.soywiz:klock-locale-metadata:$klockVersion"

                implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime-common:$serialization_version"
            }
        }
        commonTest {
            dependencies {
                implementation kotlin('test-common')
                implementation kotlin('test-annotations-common')
            }
        }
        jvmMain {
            dependencies {
                implementation kotlin('stdlib-jdk8')

                implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime:$serialization_version"

                implementation "io.ktor:ktor-server-netty:$ktor_version"
                implementation "io.ktor:ktor-auth:$ktor_version"
                implementation "io.ktor:ktor-server-sessions:$ktor_version"
                implementation "io.ktor:ktor-websockets:$ktor_version"
                implementation "io.ktor:ktor-jackson:$ktor_version"
                implementation 'org.jetbrains:kotlin-css-jvm:1.0.0-pre.70-kotlin-1.3.21'

                implementation "io.ktor:ktor-html-builder:$ktor_version"
                implementation "io.ktor:ktor-client-apache:$ktor_version"

                implementation 'org.xerial:sqlite-jdbc:3.25.2'
                implementation 'org.jetbrains.exposed:exposed:0.12.2'

                implementation 'org.mindrot:jbcrypt:0.4'

                implementation "de.westermann:KObserve-jvm:$observable_version"
                implementation "com.soywiz:klock-jvm:$klockVersion"
                implementation "com.soywiz:klock-locale-jvm:$klockVersion"

                implementation 'com.github.uchuhimo:konf:master-SNAPSHOT'
                implementation 'com.vladsch.flexmark:flexmark-all:0.42.10'
                api 'io.github.microutils:kotlin-logging:1.6.23'
                api 'ch.qos.logback:logback-classic:1.2.3'
                api 'org.fusesource.jansi:jansi:1.8'
            }
        }
        jvmTest {
            dependencies {
                implementation kotlin('test')
                implementation kotlin('test-junit')
            }
        }
        jsMain {
            dependencies {
                implementation kotlin('stdlib-js')

                implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime-js:$serialization_version"

                implementation "de.westermann:KObserve-js:$observable_version"
                implementation "com.soywiz:klock-js:$klockVersion"
                implementation "com.soywiz:klock-locale-js:$klockVersion"
            }
        }
        jsTest {
            dependencies {
                implementation kotlin('test-js')
            }
        }
    }
}

sass {
    main {
        srcDir = file("$projectDir/src/jsMain/resources/style")
        outDir = file("$buildDir/processedResources/js/main/style")

        exclude = "**/*.css"
    }
}


def webFolder = new File(project.buildDir, "../web")

task populateWebFolder(dependsOn: [jsMainClasses, sass]) {
    doLast {
        copy {
            from kotlin.targets.js.compilations.main.output
            from kotlin.sourceSets.jsMain.resources.srcDirs
            kotlin.targets.js.compilations.test.runtimeDependencyFiles.files.each {
                if (it.exists() && !it.isDirectory()) {
                    from zipTree(it.absolutePath).matching {
                        include '*.js'
                        exclude '*.meta.js'
                    }
                }
            }
            into webFolder
        }
    }
}

jsJar.dependsOn(populateWebFolder)

def mainClassName = 'de.kif.backend.MainKt'

task run(type: JavaExec, dependsOn: [jvmMainClasses, jsJar]) {
    main = mainClassName
    classpath {
        [
                kotlin.targets.jvm.compilations.main.output.allOutputs.files,
                configurations.jvmRuntimeClasspath,
        ]
    }
    args = []
    standardInput = System.in
}

clean.doFirst {
    delete webFolder
    delete ".sessions"
    delete "data"
}

jsJar {
    from webFolder
}

static String buildTime() {
    def format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z")
    format.setTimeZone(TimeZone.getTimeZone("UTC"))
    return format.format(new Date())
}

task jar(type: ShadowJar, dependsOn: [assemble]) {
    //minimize()

    from(webFolder) {
        into "web"
        includeEmptyDirs false
        exclude "*.js.map", "*.meta.js", "**/*.scss", "**/_*.css", "**/*.kjsm", "*.MF"
    }

    from kotlin.targets.jvm.compilations.main.runtimeDependencyFiles
    from kotlin.targets.jvm.compilations.main.output

    exclude "**/INDEX.LIST", "**/*.SF", "**/*.RSA"

    archiveBaseName.set rootProject.name
    archiveClassifier.set null
    archiveVersion.set null

    manifest {
        attributes 'Main-Class': mainClassName
        attributes "Build-Time": buildTime()
        attributes "Build-Version": project.version
        attributes "Build-Tools": "gradle-${project.getGradle().getGradleVersion()}, groovy-${GroovySystem.getVersion()}, java-${System.getProperty('java.version')}"
        attributes "Build-System": "${System.getProperty("os.name")} '${System.getProperty("os.version")}' (${System.getProperty("os.arch")})"
    }
}
