package pw.hamzantal.vagueenchants

import org.bukkit.Bukkit
import org.bukkit.event.player.PlayerJoinEvent
import org.bukkit.event.player.PlayerQuitEvent
import java.sql.Connection
import java.sql.DriverManager
import java.util.*


private var nextCheck = 0L
private var baseC: Connection = run {
	val (host, db, _, user, pass) = Config.token
	DriverManager.getConnection("jdbc:mysql://${host}:3306/${db}", user, pass)
}

val conn: Connection?
	get() {
		if (System.currentTimeMillis() > nextCheck) {
			val (host, db, _, user, pass) = Config.token
			try {
				baseC.close()
			} catch (e: Exception) {
			}
			baseC = DriverManager.getConnection("jdbc:mysql://${host}:3306/${db}", user, pass)
			nextCheck = System.currentTimeMillis() + 30 * 1000
		}
		return baseC
	}

val cachedTokens = hashMapOf<String, Long>()

fun getTokens(uuid: String): Long {
	if (cachedTokens.containsKey(uuid)) return cachedTokens[uuid]!!

	val c = conn
	if (c?.isClosed != false) return 0


	val query = c.prepareStatement("SELECT tokens FROM ${Config.token.table} WHERE uuid = ? LIMIT 1").run {
		setString(1, uuid)
		executeQuery()
	}
	if (query.next()) {
		val toReturn = query.getLong("tokens")
		query.close()
		return toReturn
	}

	return 0
}

fun setTokens(uuid: String, amount: Long, force: Boolean = false): Boolean {
	if (Bukkit.getOfflinePlayer(UUID.fromString(uuid)).isOnline) cachedTokens[uuid] = amount
	if (!force) return true

	val c = conn

	if (c?.isClosed != false) return false

	c.prepareStatement("INSERT INTO ${Config.token.table} (uuid, tokens) VALUES (?, ?) ON DUPLICATE KEY UPDATE tokens = ?")
		.run {
			setString(1, uuid)
			setLong(2, amount)
			setLong(3, amount)
			closeOnCompletion()
			return executeUpdate() == 1
		}

}

fun onJoin(e: PlayerJoinEvent) {
	val id = e.player.uuid
	cachedTokens[id] = getTokens(id)
}

fun onLeave(e: PlayerQuitEvent) {
	val id = e.player.uuid
	setTokens(id, getTokens(id), true)
	cachedTokens.remove(id)
}