import org.apache.tools.ant.filters.ReplaceTokens

import java.awt.*

// --------------- Plugins ---------------

plugins {
	id 'application'
}

// --------------- Info ---------------

version = getTagVersion('repl/')
description = 'The Dyvil REPL interactive shell'

mainClassName = 'dyvilx.tools.repl.Main'

// --------------- Dependencies ---------------

dependencies {
	// https://mvnrepository.com/artifact/org.jline/jline
	implementation group: 'org.jline', name: 'jline', version: '3.9.0'

	implementation libraryDependency
	implementation project(':compiler')
}

// --------------- Source Copying ---------------

tasks.register('copyJava', Copy) {
	it.from sourceSets.main.java
	it.into "$buildDir/src/main/java/"

	it.include '**/DyvilREPL.java'
	it.includeEmptyDirs = false

	it.filter(ReplaceTokens, beginToken: '$$', endToken: '$$', tokens: [
			replVersion: project.version
	])
}

tasks.named('compileJava', JavaCompile) {
	it.dependsOn 'copyJava'
	it.source files("$buildDir/src/main/java").builtBy('copyJava')
	it.exclude {
		final String path = it.file.path
		return path.endsWith('DyvilREPL.java') && (path.contains('repl/src/main/java') || path.contains('repl\\src\\main\\java'))
	}
}

// --------------- Running ---------------

tasks.named('run', JavaExec) {
	it.dependsOn ':build'

	it.args '--ansi', '--classpath=' + rootProject.sourceSets.test.runtimeClasspath.asPath

	it.jvmArgs '-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005'

	it.standardOutput = System.out
	it.standardInput = System.in

	it.main = mainClassName
	it.classpath = rootProject.sourceSets.test.runtimeClasspath + sourceSets.main.runtimeClasspath
}

tasks.register('saveCommand') {
	final File commandFile = new File("$buildDir/tmp/repl.command")
	it.outputs.file commandFile

	it.doLast {
		final JavaExec runRepl = tasks.run as JavaExec
		final String content = '#!/usr/bin/env bash\n' + runRepl.commandLine.collect {
			"'${ it.replace('\'', '\'"\'"\'') }'"
		}.join(' \\\n\t') + '\n'

		commandFile.text = content
		commandFile.executable = true
	}
}

tasks.register('runInTerminal') {
	it.dependsOn = tasks.run.dependsOn
	it.dependsOn 'saveCommand'

	it.doLast {
		System.setProperty('apple.awt.UIElement', 'true') // avoid dock icon
		Desktop.desktop.open(new File("$buildDir/tmp/repl.command"))
	}
}
