package ru.dbotthepony.mc.otm.client

import net.minecraftforge.client.event.ClientPlayerNetworkEvent
import net.minecraftforge.event.TickEvent
import ru.dbotthepony.mc.otm.core.util.IConditionalTickable
import ru.dbotthepony.mc.otm.core.util.ITickable
import ru.dbotthepony.mc.otm.core.util.TickList
import ru.dbotthepony.mc.otm.isClient

private val preTickList = TickList()
private val postTickList = TickList()

var LOGGED_IN = false
	private set

fun onceClient(ticker: ITickable) {
	check(isClient) { "Illegal side" }
	postTickList.once(ticker, LOGGED_IN, "Not logged in")
}

fun onceClientPre(ticker: ITickable) {
	check(isClient) { "Illegal side" }
	preTickList.once(ticker, LOGGED_IN, "Not logged in")
}

fun onceClient(inTicks: Int, ticker: Runnable) {
	check(isClient) { "Illegal side" }
	postTickList.timer(inTicks, ticker, LOGGED_IN, "Not logged in")
}

fun onceClientPre(inTicks: Int, ticker: Runnable) {
	check(isClient) { "Illegal side" }
	preTickList.timer(inTicks, ticker, LOGGED_IN, "Not logged in")
}

fun tickClient(ticker: IConditionalTickable) {
	check(isClient) { "Illegal side" }
	postTickList.add(ticker, LOGGED_IN, "Not logged in")
}

fun tickClientPre(ticker: IConditionalTickable) {
	check(isClient) { "Illegal side" }
	preTickList.add(ticker, LOGGED_IN, "Not logged in")
}

fun tickUntilClient(ticker: () -> Boolean) {
	tickClient(IConditionalTickable.wrap(ticker))
}

fun tickUntilClientPre(ticker: () -> Boolean) {
	tickClientPre(IConditionalTickable.wrap(ticker))
}

fun tickWhileClient(condition: () -> Boolean, ticker: () -> Unit) {
	tickClient(IConditionalTickable.wrap(condition, ticker))
}

fun tickWhileClientPre(condition: () -> Boolean, ticker: () -> Unit) {
	tickClientPre(IConditionalTickable.wrap(condition, ticker))
}

fun onClientTick(event: TickEvent.ClientTickEvent) {
	if (event.phase == TickEvent.Phase.START) {
		preTickList.tick()
	} else {
		postTickList.tick()
	}
}

fun onClientDisconnected(event: ClientPlayerNetworkEvent.LoggingOut) {
	LOGGED_IN = false

	preTickList.clear()
	postTickList.clear()
}

fun onClientConnected(event: ClientPlayerNetworkEvent.LoggingIn) {
	LOGGED_IN = true

	preTickList.clear()
	postTickList.clear()
}
