package xyz.apiote.bimba.czwek.api

import android.content.Context
import android.graphics.*
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.graphics.drawable.LayerDrawable
import android.os.Parcelable
import android.text.format.DateUtils
import android.util.Log
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.graphics.ColorUtils.HSLToColor
import androidx.core.graphics.drawable.toBitmap
import kotlinx.parcelize.Parcelize
import org.yaml.snakeyaml.Yaml
import xyz.apiote.bimba.czwek.R
import xyz.apiote.bimba.czwek.dpToPixel
import xyz.apiote.bimba.czwek.dpToPixelI
import xyz.apiote.fruchtfleisch.Reader
import java.io.InputStream
import java.time.Instant
import java.time.ZoneId
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import java.time.temporal.ChronoUnit
import java.util.*
import java.util.zip.Adler32
import kotlin.math.abs
import kotlin.math.pow

class TrafficFormatException(override val message: String) : IllegalArgumentException()
class UnknownResourceVersion(val resource: String, val version: ULong) : Exception()

data class BimbaInfo(
	val contact: Map<String, String>,
)

data class Bimba(
	val info: BimbaInfo,
	val servers: List<Map<String, String>>,
	val security: List<Map<String, List<*>>>
) {
	companion object {
		@Suppress("UNCHECKED_CAST")
		fun unmarshal(stream: InputStream): Bimba {
			val map = Yaml().load(stream) as HashMap<String, *>
			val contact =
				if (map["info"] is Map<*, *> && (map["info"] as Map<*, *>).keys.all { it is String }) {
					(map["info"] as Map<String, *>)["contact"]
				} else {
					throw TrafficFormatException("invalid info format")
				}
			val contactMap =
				if (contact is Map<*, *> && contact.all { it.key is String && it.value is String }) {
					contact as Map<String, String>
				} else {
					throw TrafficFormatException("invalid contact format")
				}
			val servers = if (map["servers"] is List<*> && (map["servers"] as List<*>).all { server ->
					server is Map<*, *> && server.all { it.key is String && it.value is String }
				}) {
				map["servers"] as List<Map<String, String>>
			} else {
				throw TrafficFormatException("invalid servers format")
			}
			val security =
				if (map["security"] is List<*> && (map["security"] as List<*>).all { security ->
						security is Map<*, *> && security.all { it.key is String && it.value is List<*> }
					}) {
					map["security"] as List<Map<String, List<*>>>
				} else {
					throw TrafficFormatException("invalid security format")
				}
			val bimba = Bimba(BimbaInfo(contactMap), servers, security)
			bimba.validate()
			return bimba
		}
	}

	fun isPrivate(): Boolean {
		return security.size == 1 && security[0]["api_key"] != null
	}

	fun isRateLimited(): Boolean {
		val items = security.foldRight(0b00) { map, acc ->
			acc or when {
				map.containsKey("api_key") -> 0b10
				map.isEmpty() -> 0b01
				else -> 0b00
			}
		}
		Log.i("Rate limited", "${this}, $items")
		return security.size == 2 && items == 0b11
	}

	private fun validate() {
		if (servers.isEmpty() || servers[0]["url"] == null) {
			throw TrafficFormatException("no server in info")
		}
		if (security.isEmpty()) {
			throw TrafficFormatException("no security")
		}
	}
}

@Parcelize
data class PositionV1(
	val latitude: Double, val longitude: Double
) : Parcelable {
	fun isZero(): Boolean {
		return latitude == 0.0 && longitude == 0.0
	}

	override fun toString(): String = "$latitude,$longitude"


	companion object {
		fun unmarshal(stream: InputStream): PositionV1 {
			val reader = Reader(stream)
			return PositionV1(
				reader.readFloat64(), reader.readFloat64()
			)
		}
	}
}

data class FeedInfoV1(
	val name: String,
	val id: String,
	val attribution: String,
	val description: String,
	val lastUpdate: ZonedDateTime
) {
	companion object {
		fun unmarshal(stream: InputStream): FeedInfoV1 {
			val reader = Reader(stream)
			return FeedInfoV1(
				reader.readString(),
				reader.readString(),
				reader.readString(),
				reader.readString(),
				ZonedDateTime.parse(reader.readString(), DateTimeFormatter.ISO_DATE_TIME)
			)
		}
	}

	fun formatDate(): String {
		return lastUpdate.format(
			DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).withLocale(Locale.getDefault())
		)
	}
}

data class AlertV1(
	val header: String,
	val Description: String,
	val Url: String,
	val Cause: ULong,  // todo [3.1] enum
	val Effect: ULong  // todo [3.1] enum
) {
	companion object {
		fun unmarshal(stream: InputStream): AlertV1 {
			val reader = Reader(stream)
			val header = reader.readString()
			val description = reader.readString()
			val url = reader.readString()
			val cause = reader.readUInt().toULong()
			val effect = reader.readUInt().toULong()
			return AlertV1(header, description, url, cause, effect)
		}
	}
}

data class Time(
	val Hour: UInt, val Minute: UInt, val Second: UInt, val DayOffset: Byte, val Zone: String
) {
	companion object {
		fun unmarshal(stream: InputStream): Time {
			val reader = Reader(stream)
			return Time(
				reader.readUInt().toULong().toUInt(),
				reader.readUInt().toULong().toUInt(),
				reader.readUInt().toULong().toUInt(),
				reader.readI8(),
				reader.readString()
			)
		}
	}
}

data class ColourV1(val R: UByte, val G: UByte, val B: UByte) {
	companion object {
		fun unmarshal(stream: InputStream): ColourV1 {
			val reader = Reader(stream)
			return ColourV1(
				reader.readU8(), reader.readU8(), reader.readU8()
			)
		}
	}

	fun toInt(): Int {
		var rgb = 0xff
		rgb = (rgb shl 8) + R.toInt()
		rgb = (rgb shl 8) + G.toInt()
		rgb = (rgb shl 8) + B.toInt()
		return rgb
	}
}

data class VehicleV1(
	val ID: String,
	val Position: PositionV1,
	val Capabilities: UShort,
	val Speed: Float,
	val Line: LineStubV1,
	val Headsign: String,
	val CongestionLevel: ULong,
	val OccupancyStatus: ULong
) : Locatable {
	enum class Capability(val bit: UShort) {
		RAMP(0b0001u), LOW_FLOOR(0b0010u), LOW_ENTRY(0b0001_0000_0000u), AC(0b0100u), BIKE(0b1000u), VOICE(
			0b0001_0000u
		),
		TICKET_MACHINE(0b0010_0000u), TICKET_DRIVER(0b0100_0000u), USB_CHARGING(0b1000_0000u)
	}

	override fun id(): String = ID

	override fun icon(context: Context, scale: Float): Drawable {
		return BitmapDrawable(context.resources, Line.icon(context, scale))
	}

	override fun location(): PositionV1 = Position

	fun congestion(context: Context): String {
		return when (val r = CongestionLevel.toUInt()) { // todo [3.1] enum
			0u -> context.getString(R.string.congestion_unknown)
			1u -> context.getString(R.string.congestion_smooth)
			2u -> context.getString(R.string.congestion_stop_and_go)
			3u -> context.getString(R.string.congestion_congestion)
			4u -> context.getString(R.string.congestion_jams)
			else -> throw UnknownResourceVersion("Congestion/$r", 1u)
		}
	}

	fun occupancy(context: Context): String {
		return when (val r = OccupancyStatus.toUInt()) { // todo [3.1] enum
			0u -> context.getString(R.string.occupancy_unknown)
			1u -> context.getString(R.string.occupancy_empty)
			2u -> context.getString(R.string.occupancy_many_seats)
			3u -> context.getString(R.string.occupancy_few_seats)
			4u -> context.getString(R.string.occupancy_standing_only)
			5u -> context.getString(R.string.occupancy_crowded)
			6u -> context.getString(R.string.occupancy_full)
			7u -> context.getString(R.string.occupancy_wont_let)
			else -> throw UnknownResourceVersion("Occupancy/$r", 1u)
		}
	}

	companion object {
		fun unmarshal(stream: InputStream): VehicleV1 {
			val reader = Reader(stream)
			return VehicleV1(
				reader.readString(),
				PositionV1.unmarshal(stream),
				reader.readU16(),
				reader.readFloat32(),
				LineStubV1.unmarshal(stream),
				reader.readString(),
				reader.readUInt().toULong(),
				reader.readUInt().toULong()
			)
		}
	}

	fun getCapability(field: Capability): Boolean {
		return Capabilities.and(field.bit) != (0).toUShort()
	}
}

data class LineStubV1(
	val name: String, val kind: LineTypeV1, val colour: ColourV1
) : LineAbstract {
	companion object {
		fun unmarshal(stream: InputStream): LineStubV1 {
			val reader = Reader(stream)
			return LineStubV1(
				reader.readString(),
				LineTypeV1.of(reader.readUInt().toULong().toUInt()),
				ColourV1.unmarshal(stream)
			)
		}
	}

	fun icon(context: Context, scale: Float = 1f): Bitmap {
		return super.icon(context, kind, colour, scale)
	}
}

data class DepartureV1(
	val ID: String,
	val time: Time,
	val status: ULong,
	val isRealtime: Boolean,
	val vehicle: VehicleV1,
	val boarding: UByte
) {

	fun statusText(context: Context?): String {
		val now = Instant.now().atZone(ZoneId.systemDefault())
		val departureTime = ZonedDateTime.of(
			now.year, now.monthValue, now.dayOfMonth,
			time.Hour.toInt(), time.Minute.toInt(), time.Second.toInt(), 0, ZoneId.of(time.Zone)
		).plus(time.DayOffset.toLong(), ChronoUnit.DAYS)
		return when (val r = status.toUInt()) {
			0u -> DateUtils.getRelativeTimeSpanString(
				departureTime.toEpochSecond() * 1000,
				now.toEpochSecond() * 1000,
				DateUtils.MINUTE_IN_MILLIS,
				DateUtils.FORMAT_ABBREV_RELATIVE
			).toString()
			1u -> context?.getString(R.string.departure_momentarily) ?: "momentarily"
			2u -> context?.getString(R.string.departure_now) ?: "now"
			3u -> context?.getString(R.string.departure_departed) ?: "departed"
			else -> throw UnknownResourceVersion("VehicleStatus/$r", 1u)
		}
	}

	fun timeString(context: Context): String {
		return if (isRealtime) {
			context.getString(
				R.string.at_time_realtime, time.Hour.toInt(), time.Minute.toInt(), time.Second.toInt()
			)
		} else {
			context.getString(R.string.at_time, time.Hour.toInt(), time.Minute.toInt())
		}
	}

	fun boardingText(context: Context): String {
		// todo [3.x] probably should take into account (on|off)-boarding only, on demand
		return when {
			boarding == (0b0000_0000).toUByte() -> context.getString(R.string.no_boarding)
			boarding.and(0b0011_0011u) == (0b0000_0001).toUByte() -> context.getString(R.string.on_boarding)
			boarding.and(0b0011_0011u) == (0b0001_0000).toUByte() -> context.getString(R.string.off_boarding)
			boarding.and(0b0011_0011u) == (0b0001_0001).toUByte() -> context.getString(R.string.boarding)
			else -> context.getString(R.string.on_demand)
		}
	}

	companion object {
		fun unmarshal(stream: InputStream): DepartureV1 {
			val reader = Reader(stream)
			val id = reader.readString()
			val time = Time.unmarshal(stream)
			val status = reader.readUInt().toULong()
			val isRealtime = reader.readBoolean()
			val vehicle = VehicleV1.unmarshal(stream)
			val boarding = reader.readU8()
			return DepartureV1(id, time, status, isRealtime, vehicle, boarding)
		}
	}
}

interface QueryableV1
interface Locatable {
	fun icon(context: Context, scale: Float = 1f): Drawable
	fun location(): PositionV1
	fun id(): String
}

class ErrorLocatable(val stringResource: Int) : Locatable {
	override fun icon(context: Context, scale: Float): Drawable {
		return AppCompatResources.getDrawable(context, R.drawable.error_other)!!
	}

	override fun location(): PositionV1 {
		return PositionV1(0.0, 0.0)
	}

	override fun id(): String {
		return "ERROR"
	}
}

@Parcelize
data class StopV1(
	val code: String,
	val name: String,
	val zone: String,
	val position: PositionV1,
	val changeOptions: List<ChangeOptionV1>
) : QueryableV1, Locatable, Parcelable {

	override fun icon(context: Context, scale: Float): Drawable {
		val saturationArray = arrayOf(0.5f, 0.65f, 0.8f)
		val sal = saturationArray.size
		val lightnessArray = arrayOf(.5f)
		val lal = lightnessArray.size
		val md = Adler32().let {
			it.update(name.toByteArray())
			it.value
		}
		val h = md % 359f
		val s = saturationArray[(md / 360 % sal).toInt()]
		val l = lightnessArray[(md / 360 / sal % lal).toInt()]
		val fg = AppCompatResources.getDrawable(context, R.drawable.stop)
		val bg = AppCompatResources.getDrawable(context, R.drawable.stop_bg)!!.mutate().apply {
			setTint(HSLToColor(arrayOf(h, s, l).toFloatArray()))
		}
		return BitmapDrawable(
			context.resources,
			LayerDrawable(arrayOf(bg, fg)).mutate()
				.toBitmap(dpToPixelI(24f / scale), dpToPixelI(24f / scale), Bitmap.Config.ARGB_8888)
		)
	}

	override fun id(): String = code

	override fun location(): PositionV1 = position

	override fun toString(): String {
		var result = "$name ($code) [$zone] $position\n"
		for (chOpt in changeOptions) result += "${chOpt.line} → ${chOpt.headsign}\n"
		return result
	}

	fun changeOptions(context: Context): Pair<String, String> {
		return Pair(changeOptions.groupBy { it.line }
			.map { Pair(it.key, it.value.joinToString { co -> co.headsign }) }.joinToString {
				context.getString(
					R.string.vehicle_headsign, it.first, it.second
				)
			},
			changeOptions.groupBy { it.line }
				.map { Pair(it.key, it.value.joinToString { co -> co.headsign }) }.joinToString {
					context.getString(
						R.string.vehicle_headsign_content_description, it.first, it.second
					)
				})
	}

	companion object {
		fun unmarshal(stream: InputStream): StopV1 {
			val reader = Reader(stream)
			val code = reader.readString()
			val name = reader.readString()
			val zone = reader.readString()
			val position = PositionV1.unmarshal(stream)
			val chOptionsNum = reader.readUInt().toULong()
			val changeOptions = mutableListOf<ChangeOptionV1>()
			for (i in 0UL until chOptionsNum) {
				changeOptions.add(ChangeOptionV1.unmarshal(stream))
			}
			return StopV1(
				name = name, code = code, zone = zone, position = position, changeOptions = changeOptions
			)
		}
	}
}

interface LineAbstract {
	fun textColour(c: ColourV1): Int {
		val black = relativeLuminance(ColourV1(0u, 0u, 0u)) + .05
		val white = relativeLuminance(ColourV1(255u, 255u, 255u)) + .05
		val colour = relativeLuminance(c) + .05
		return if ((white / colour) > (colour / black)) {
			Color.WHITE
		} else {
			Color.BLACK
		}
	}

	private fun relativeLuminance(colour: ColourV1): Double {
		val r = fromSRGB(colour.R.toDouble() / 0xff)
		val g = fromSRGB(colour.G.toDouble() / 0xff)
		val b = fromSRGB(colour.B.toDouble() / 0xff)
		return 0.2126 * r + 0.7152 * g + 0.0722 * b
	}

	private fun fromSRGB(part: Double): Double {
		return if (part <= 0.03928) {
			part / 12.92
		} else {
			((part + 0.055) / 1.055).pow(2.4)
		}
	}

	fun icon(context: Context, type: LineTypeV1, colour: ColourV1, scale: Float): Bitmap {
		val drawingBitmap = Bitmap.createBitmap(
			dpToPixelI(24f / scale), dpToPixelI(24f / scale), Bitmap.Config.ARGB_8888
		)
		val canvas = Canvas(drawingBitmap)

		canvas.drawPath(getSquirclePath(
			dpToPixel(.8f / scale), dpToPixel(.8f / scale), dpToPixelI(11.2f / scale)
		), Paint().apply { color = textColour(colour) })
		canvas.drawPath(getSquirclePath(
			dpToPixel(1.6f / scale), dpToPixel(1.6f / scale), dpToPixelI(10.4f / scale)
		), Paint().apply { color = colour.toInt() })

		val iconID = when (type) {
			LineTypeV1.BUS -> R.drawable.bus_black
			LineTypeV1.TRAM -> R.drawable.tram_black
			LineTypeV1.UNKNOWN -> R.drawable.vehicle_black
		}
		val icon = AppCompatResources.getDrawable(context, iconID)?.mutate()?.apply {
			setTint(textColour(colour))
		}?.toBitmap(dpToPixelI(19.2f / scale), dpToPixelI(19.2f / scale), Bitmap.Config.ARGB_8888)
		canvas.drawBitmap(
			icon!!, dpToPixel(2.4f / scale), dpToPixel(2.4f / scale), Paint()
		)
		return drawingBitmap
	}

	private fun getSquirclePath(
		left: Float, top: Float, radius: Int
	): Path {
		val radiusToPow = (radius * radius * radius).toDouble()
		val path = Path()
		path.moveTo(-radius.toFloat(), 0f)
		for (x in -radius..radius) path.lineTo(
			x.toFloat(), Math.cbrt(radiusToPow - abs(x * x * x)).toFloat()
		)
		for (x in radius downTo -radius) path.lineTo(
			x.toFloat(), -Math.cbrt(radiusToPow - abs(x * x * x)).toFloat()
		)
		path.close()
		val matrix = Matrix()
		matrix.postTranslate((left + radius), (top + radius))
		path.transform(matrix)
		return path
	}
}

data class Line(
	val colour: ColourV1,
	val type: LineTypeV1,
	val headsignsThere: List<String>,
	val headsignsBack: List<String>,
	val graphThere: LineGraph,
	val graphBack: LineGraph,
	val name: String
) : QueryableV1, LineAbstract {
	override fun toString(): String {
		return "$name ($type) [$colour]\n→ [${headsignsThere.joinToString()}]\n→ [${headsignsBack.joinToString()}]\n"
	}

	fun icon(context: Context, scale: Float = 1f): Bitmap {
		return super.icon(context, type, colour, scale)
	}

	companion object {
		fun unmarshal(stream: InputStream): Line {
			val reader = Reader(stream)
			val colour = ColourV1.unmarshal(stream)
			val type = reader.readUInt()
			val headsignsThereNum = reader.readUInt().toULong()
			val headsignsThere = mutableListOf<String>()
			for (i in 0UL until headsignsThereNum) {
				headsignsThere.add(reader.readString())
			}
			val headsignsBackNum = reader.readUInt().toULong()
			val headsignsBack = mutableListOf<String>()
			for (i in 0UL until headsignsBackNum) {
				headsignsBack.add(reader.readString())
			}
			val graphThere = LineGraph.unmarshal(stream)
			val graphBack = LineGraph.unmarshal(stream)
			val name = reader.readString()
			return Line(
				name = name,
				colour = colour,
				type = LineTypeV1.of(type.toULong().toUInt()),
				headsignsThere = headsignsThere,
				headsignsBack = headsignsBack,
				graphThere = graphThere,
				graphBack = graphBack
			)
		}
	}
}

enum class LineTypeV1 {
	UNKNOWN, TRAM, BUS;

	companion object {
		fun of(type: UInt): LineTypeV1 {
			return when (type) {
				0u -> valueOf("UNKNOWN")
				1u -> valueOf("TRAM")
				2u -> valueOf("BUS")
				else -> throw UnknownResourceVersion("LineType/$type", 1u)
			}
		}
	}
}

@Parcelize
data class ChangeOptionV1(val line: String, val headsign: String):Parcelable {
	companion object {
		fun unmarshal(stream: InputStream): ChangeOptionV1 {
			val reader = Reader(stream)
			return ChangeOptionV1(line = reader.readString(), headsign = reader.readString())
		}
	}
}

data class LineGraph(
	val stops: List<StopStub>,
	val nextNodes: Map<Long, List<Long>>,
	val prevNodes: Map<Long, List<Long>>
) {
	companion object {
		fun unmarshal(stream: InputStream): LineGraph {
			val reader = Reader(stream)
			val stopsNum = reader.readUInt().toULong()
			val stops = mutableListOf<StopStub>()
			for (i in 0UL until stopsNum) {
				stops.add(StopStub.unmarshal(stream))
			}
			val nextNodesNum = reader.readUInt().toULong()
			val nextNodes = mutableMapOf<Long, List<Long>>()
			for (i in 0UL until nextNodesNum) {
				val from = reader.readInt().toLong()
				val toNum = reader.readUInt().toULong()
				val to = mutableListOf<Long>()
				for (j in 0UL until toNum) {
					to.add(reader.readInt().toLong())
				}
				nextNodes[from] = to
			}
			val prevNodesNum = reader.readUInt().toULong()
			val prevNodes = mutableMapOf<Long, List<Long>>()
			for (i in 0UL until prevNodesNum) {
				val from = reader.readInt().toLong()
				val toNum = reader.readUInt().toULong()
				val to = mutableListOf<Long>()
				for (j in 0UL until toNum) {
					to.add(reader.readInt().toLong())
				}
				prevNodes[from] = to
			}

			return LineGraph(stops = stops, nextNodes = nextNodes, prevNodes = prevNodes)
		}
	}
}

data class StopStub(val name: String, val code: String, val zone: String, val onDemand: Boolean) {
	companion object {
		fun unmarshal(stream: InputStream): StopStub {
			val reader = Reader(stream)
			return StopStub(
				code = reader.readString(),
				name = reader.readString(),
				zone = reader.readString(),
				onDemand = reader.readBoolean()
			)
		}
	}
}