package ru.dbotthepony.kstarbound.util

import ru.dbotthepony.kstarbound.Starbound
import java.io.File

object AssetPathStack {
	private val _stack = object : ThreadLocal<ArrayDeque<String>>() {
		override fun initialValue(): ArrayDeque<String> {
			return ArrayDeque()
		}
	}

	private val stack: ArrayDeque<String> get() = _stack.get()

	fun push(value: String) {
		stack.addLast(value)
	}

	fun pushFilename(value: String) {
		push(value.substringBefore(':').substringBeforeLast('/'))
	}

	fun last() = stack.lastOrNull() ?: "/"
	fun pop() = stack.removeLast()

	inline fun <T> block(path: String, block: (String) -> T): T {
		try {
			push(path)
			return block.invoke(path)
		} finally {
			pop()
		}
	}

	inline operator fun <T> invoke(path: String, block: (String) -> T) = block(path, block)

	private fun remap(a: String, b: String): String {
		if (b.isEmpty())
			return a
		if (b[0] == '/')
			return b

		return Starbound.STRINGS.intern("$a/$b")
	}

	fun remap(path: String): String {
		return remap(last(), path)
	}

	fun remapSafe(path: String): String {
		return remap(last(), path)
	}

	fun relativeTo(base: String, path: String): String {
		if (path.isNotEmpty() && path[0] == '/')
			return path

		return if (base.endsWith('/')) "$base$path" else "$base/$path"
	}
}
