package xyz.apiote.bimba.czwek.repo

import android.content.Context
import android.net.ConnectivityManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import xyz.apiote.bimba.czwek.api.DeparturesResponse
import xyz.apiote.bimba.czwek.api.DeparturesResponseDev
import xyz.apiote.bimba.czwek.api.DeparturesResponseV1
import xyz.apiote.bimba.czwek.api.DeparturesResponseV2
import xyz.apiote.bimba.czwek.api.ErrorResponse
import xyz.apiote.bimba.czwek.api.LineResponse
import xyz.apiote.bimba.czwek.api.LineResponseDev
import xyz.apiote.bimba.czwek.api.LineResponseV1
import xyz.apiote.bimba.czwek.api.LineV1
import xyz.apiote.bimba.czwek.api.LineV2
import xyz.apiote.bimba.czwek.api.LocatablesResponse
import xyz.apiote.bimba.czwek.api.LocatablesResponseDev
import xyz.apiote.bimba.czwek.api.LocatablesResponseV1
import xyz.apiote.bimba.czwek.api.LocatablesResponseV2
import xyz.apiote.bimba.czwek.api.PositionV1
import xyz.apiote.bimba.czwek.api.QueryablesResponse
import xyz.apiote.bimba.czwek.api.QueryablesResponseDev
import xyz.apiote.bimba.czwek.api.QueryablesResponseV1
import xyz.apiote.bimba.czwek.api.QueryablesResponseV2
import xyz.apiote.bimba.czwek.api.Server
import xyz.apiote.bimba.czwek.api.StopV1
import xyz.apiote.bimba.czwek.api.StopV2
import xyz.apiote.bimba.czwek.api.UnknownResourceException
import xyz.apiote.bimba.czwek.api.VehicleV1
import xyz.apiote.bimba.czwek.api.VehicleV2
import xyz.apiote.bimba.czwek.api.VehicleV3

// todo [3.2] in Repository check if responses are BARE or HTML

class OnlineRepository : Repository {
	override suspend fun getDepartures(
		cm: ConnectivityManager,
		feedID: String,
		stop: String,
		line: String?,
		context: Context
	): StopDepartures? {
		val result =
			xyz.apiote.bimba.czwek.api.getDepartures(cm, Server.get(context), feedID, stop, line)
		if (result.error != null) {
			if (result.stream != null) {
				val response = withContext(Dispatchers.IO) { ErrorResponse.unmarshal(result.stream) }
				throw TrafficResponseException(result.error.statusCode, response.message, result.error)
			} else {
				throw TrafficResponseException(result.error.statusCode, "", result.error)
			}
		} else {
			return when (val response =
				withContext(Dispatchers.IO) { DeparturesResponse.unmarshal(result.stream!!) }) {
				is DeparturesResponseDev -> StopDepartures(
					response.departures.map { Departure(it) },
					Stop(response.stop),
					response.alerts.map { Alert(it) })

				is DeparturesResponseV1 -> StopDepartures(
					response.departures.map { Departure(it) },
					Stop(response.stop),
					response.alerts.map { Alert(it) })

				is DeparturesResponseV2 -> StopDepartures(
					response.departures.map { Departure(it) },
					Stop(response.stop),
					response.alerts.map { Alert(it) })

				else -> null
			}
		}
	}

	override suspend fun getLocatablesIn(
		cm: ConnectivityManager,
		bl: Position,
		tr: Position,
		context: Context
	): List<Locatable>? {
		val result = xyz.apiote.bimba.czwek.api.getLocatablesIn(
			cm,
			Server.get(context),
			PositionV1(bl.latitude, bl.longitude),
			PositionV1(tr.latitude, tr.longitude)
		)
		if (result.error != null) {
			if (result.stream != null) {
				val response = withContext(Dispatchers.IO) { ErrorResponse.unmarshal(result.stream) }
				throw TrafficResponseException(result.error.statusCode, response.message, result.error)
			} else {
				throw TrafficResponseException(result.error.statusCode, "", result.error)
			}
		} else {
			return when (val response =
				withContext(Dispatchers.IO) { LocatablesResponse.unmarshal(result.stream!!) }) {
				is LocatablesResponseDev -> response.locatables.map {
					when (it) {
						is StopV2 -> Stop(it)
						is VehicleV3 -> Vehicle(it)
						else -> throw UnknownResourceException("locatables", it::class)
					}
				}

				is LocatablesResponseV1 -> response.locatables.map {
					when (it) {
						is StopV1 -> Stop(it)
						is VehicleV1 -> Vehicle(it)
						else -> throw UnknownResourceException("locatables", it::class)
					}
				}

				is LocatablesResponseV2 -> response.locatables.map {
					when (it) {
						is StopV2 -> Stop(it)
						is VehicleV2 -> Vehicle(it)
						else -> throw UnknownResourceException("locatables", it::class)
					}
				}

				else -> null
			}
		}
	}

	override suspend fun getLine(
		cm: ConnectivityManager, feedID: String, line: String, context: Context
	): Line? {
		val result = xyz.apiote.bimba.czwek.api.getLine(cm, Server.get(context), feedID, line)
		if (result.error != null) {
			if (result.stream != null) {
				val response = withContext(Dispatchers.IO) { ErrorResponse.unmarshal(result.stream) }
				throw TrafficResponseException(result.error.statusCode, response.message, result.error)
			} else {
				throw TrafficResponseException(result.error.statusCode, "", result.error)
			}
		} else {
			return when (val response =
				withContext(Dispatchers.IO) { LineResponse.unmarshal(result.stream!!) }) {
				is LineResponseDev -> Line(response.line)
				is LineResponseV1 -> Line(response.line)
				else -> null
			}
		}
	}

	override suspend fun queryQueryables(
		cm: ConnectivityManager, query: String, context: Context
	): List<Queryable>? {
		return getQueryables(cm, query, null, context, "query")
	}

	override suspend fun locateQueryables(
		cm: ConnectivityManager, position: Position, context: Context
	): List<Queryable>? {
		return getQueryables(cm, null, position, context, "locate")
	}

	private suspend fun getQueryables(
		cm: ConnectivityManager, query: String?, position: Position?, context: Context, type: String
	): List<Queryable>? {
		val result = when (type) {
			"query" -> {
				xyz.apiote.bimba.czwek.api.queryQueryables(cm, Server.get(context), query!!, limit = 12)
			}

			"locate" -> xyz.apiote.bimba.czwek.api.locateQueryables(
				cm, Server.get(context), PositionV1(position!!.latitude, position.longitude)
			)

			else -> throw RuntimeException("Unknown query type $type")
		}
		if (result.error != null) {
			if (result.stream != null) {
				val response = withContext(Dispatchers.IO) { ErrorResponse.unmarshal(result.stream) }
				throw TrafficResponseException(result.error.statusCode, response.message, result.error)
			} else {
				throw TrafficResponseException(result.error.statusCode, "", result.error)
			}
		} else {
			return when (val response =
				withContext(Dispatchers.IO) { QueryablesResponse.unmarshal(result.stream!!) }) {
				is QueryablesResponseDev -> response.queryables.map {
					when (it) {
						is StopV2 -> Stop(it)
						is LineV2 -> Line(it)
						else -> throw UnknownResourceException("queryablesV2", it::class)
					}
				}

				is QueryablesResponseV1 -> response.queryables.map {
					when (it) {
						is StopV1 -> Stop(it)
						else -> throw UnknownResourceException("queryablesV1", it::class)
					}
				}

				is QueryablesResponseV2 -> response.queryables.map {
					when (it) {
						is StopV2 -> Stop(it)
						is LineV1 -> Line(it)
						else -> throw UnknownResourceException("queryablesV2", it::class)
					}
				}

				else -> null
			}
		}
	}
}