package xyz.apiote.bimba.czwek.dashboard.ui.map

import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.ConnectivityManager
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.constraintlayout.widget.Group
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import kotlinx.coroutines.launch
import xyz.apiote.bimba.czwek.R
import xyz.apiote.bimba.czwek.api.*
import xyz.apiote.bimba.czwek.departures.DeparturesActivity

class MapViewModel : ViewModel() {

	private val _locatables = MutableLiveData<List<Locatable>>()
	val locatables: MutableLiveData<List<Locatable>> = _locatables

	fun getLocatablesIn(cm: ConnectivityManager, server: Server, bl: PositionV1, tr: PositionV1) {
		viewModelScope.launch {
			val result = xyz.apiote.bimba.czwek.api.getLocatablesIn(cm, server, bl, tr)
			if (result.error != null) {
				_locatables.value = listOf(ErrorLocatable(result.error.stringResource))
				if (result.stream != null) {
					Log.w(
						"Map",
						"${result.error.statusCode}, ${ErrorResponse.unmarshal(result.stream).message}"
					)
				} else {
					Log.w("Map", "${result.error.statusCode}")
				}
				return@launch
			} else {
				_locatables.value = when (val response = LocatablesResponse.unmarshal(result.stream!!)) {
					is LocatablesResponseDev -> response.locatables
					is LocatablesResponseV1 -> response.locatables
					else -> null
				}
			}
		}
	}
}

class MapBottomSheet(private val locatable: Locatable) : BottomSheetDialogFragment() {
	companion object {
		const val TAG = "MapBottomSheet"
	}

	private fun showVehicle(content: View, vehicle: VehicleV1) {
		content.findViewById<Group>(R.id.stop_group).visibility = View.GONE
		content.findViewById<Group>(R.id.vehicle_group).visibility = View.VISIBLE

		context?.let { ctx ->
			content.findViewById<TextView>(R.id.title).apply {
				text = ctx.getString(R.string.vehicle_headsign, vehicle.Line.name, vehicle.Headsign)
				contentDescription = ctx.getString(
					R.string.vehicle_headsign_content_description,
					vehicle.Line.name,
					vehicle.Headsign
				)
			}
			// todo units -- [3.1] settings or system-based
			content.findViewById<TextView>(R.id.speed_text).text =
				ctx.getString(R.string.speed_in_km_per_h, vehicle.Speed * 3.6)
			content.findViewById<TextView>(R.id.congestion_text).text = vehicle.congestion(ctx)
			content.findViewById<TextView>(R.id.occupancy_text).text = vehicle.occupancy(ctx)
			content.findViewById<ImageView>(R.id.ac).visibility =
				if (vehicle.getCapability(VehicleV1.Capability.AC)) {
					View.VISIBLE
				} else {
					View.GONE
				}
			content.findViewById<ImageView>(R.id.bike).visibility =
				if (vehicle.getCapability(VehicleV1.Capability.BIKE)) {
					View.VISIBLE
				} else {
					View.GONE
				}
			content.findViewById<ImageView>(R.id.voice).visibility =
				if (vehicle.getCapability(VehicleV1.Capability.VOICE)) {
					View.VISIBLE
				} else {
					View.GONE
				}
			content.findViewById<ImageView>(R.id.ticket).visibility =
				if (vehicle.let {
						it.getCapability(VehicleV1.Capability.TICKET_DRIVER) || it.getCapability(VehicleV1.Capability.TICKET_MACHINE)
					}) {
					View.VISIBLE
				} else {
					View.GONE
				}
			content.findViewById<ImageView>(R.id.usb).visibility =
				if (vehicle.getCapability(VehicleV1.Capability.USB_CHARGING)) {
					View.VISIBLE
				} else {
					View.GONE
				}
		}
	}

	private fun showStop(content: View, stop: StopV1) {
		context?.let { ctx ->
			content.findViewById<Group>(R.id.stop_group).visibility = View.VISIBLE
			content.findViewById<Group>(R.id.vehicle_group).visibility = View.GONE
			content.findViewById<TextView>(R.id.title).text =
				context?.getString(R.string.stop_title, stop.name, stop.code)
			content.findViewById<Button>(R.id.departures_button).setOnClickListener {
				val intent = Intent(ctx, DeparturesActivity::class.java).apply {
					putExtra("code", stop.code)
					putExtra("name", stop.name)
				}
				startActivity(intent)
			}
			content.findViewById<Button>(R.id.navigation_button).setOnClickListener {
				try {
					startActivity(
						Intent(
							Intent.ACTION_VIEW,
							Uri.parse("geo:${stop.location().latitude},${stop.location().longitude}")
						)
					)
				} catch (_: ActivityNotFoundException) {
					Toast.makeText(context, ctx.getString(R.string.no_map_app), Toast.LENGTH_SHORT).show()
				}
			}

			stop.changeOptions(ctx).let { changeOptions ->
				content.findViewById<TextView>(R.id.change_options).apply {
					text = changeOptions.first
					contentDescription = changeOptions.second
				}
			}
		}
	}


	override fun onCreateView(
		inflater: LayoutInflater,
		container: ViewGroup?,
		savedInstanceState: Bundle?
	): View {
		val content = inflater.inflate(R.layout.map_bottom_sheet, container, false)
		content.apply {
			when (locatable) {
				is VehicleV1 -> {
					showVehicle(this, locatable)
				}
				is StopV1 -> {
					showStop(this, locatable)
				}
			}
		}
		//(dialog as BottomSheetDialog).behavior.peekHeight = dpToPixelI(90f)

		return content
	}
}