package xyz.apiote.bimba.czwek.search

import android.content.Context
import android.content.Intent
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.net.ConnectivityManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.view.WindowCompat
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.coroutines.*
import xyz.apiote.bimba.czwek.R
import xyz.apiote.bimba.czwek.api.*
import xyz.apiote.bimba.czwek.databinding.ActivityResultsBinding
import xyz.apiote.bimba.czwek.departures.DeparturesActivity
import java.io.InputStream

class ResultsActivity : AppCompatActivity(), LocationListener {
	enum class Mode {
		MODE_LOCATION, MODE_SEARCH
	}

	private var _binding: ActivityResultsBinding? = null
	private val binding get() = _binding!!

	private lateinit var adapter: BimbaResultsAdapter

	private val handler = Handler(Looper.getMainLooper())
	private var runnable = Runnable {}

	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		_binding = ActivityResultsBinding.inflate(layoutInflater)
		setContentView(binding.root)

		binding.resultsRecycler.layoutManager = LinearLayoutManager(this)
		adapter = BimbaResultsAdapter(layoutInflater, this, listOf()) {
			when (it) {
				is StopV1 -> {
					val intent = Intent(this, DeparturesActivity::class.java).apply {
						putExtra("code", it.code)
						putExtra("name", it.name)
					}
					startActivity(intent)
				}
				is Line -> {
					TODO("[3.1] start line graph activity")
				}
			}
		}
		binding.resultsRecycler.adapter = adapter
		setSupportActionBar(binding.topAppBar)

		WindowCompat.setDecorFitsSystemWindows(window, false)

		@Suppress("DEPRECATION")  // fixme later getSerializable in API>=33
		when (intent.extras?.get("mode")) {
			Mode.MODE_LOCATION -> {
				supportActionBar?.title = getString(R.string.stops_nearby)
				locate()
			}
			Mode.MODE_SEARCH -> {
				val query = intent.extras?.getString("query")!!
				supportActionBar?.title = getString(R.string.results_for, query)
				getQueryablesByQuery(Server.get(this), query)
			}
		}
	}

	private fun locate() {
		try {
			val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
			locationManager.requestLocationUpdates(
				LocationManager.GPS_PROVIDER, 1000 * 60 * 10, 100f, this
			)
			handler.removeCallbacks(runnable)
			runnable = Runnable {
				showError(Error(0, R.string.error_gps, R.drawable.error_gps))
			}
			handler.postDelayed(runnable, 60 * 1000)
			locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
				?.let { onLocationChanged(it) }
		} catch (_: SecurityException) {
			// this won’t happen because we don’t start this activity without location permission
		}
	}

	override fun onLocationChanged(location: Location) {
		handler.removeCallbacks(runnable)
		getQueryablesByLocation(Server.get(this), PositionV1(location.latitude, location.longitude))
	}

	override fun onResume() {
		super.onResume()
		@Suppress("DEPRECATION")  // fixme later getSerializable in API>=33
		if (intent.extras?.get("mode") == Mode.MODE_LOCATION) {
			locate()
		}
	}

	override fun onPause() {
		super.onPause()
		val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
		locationManager.removeUpdates(this)
		handler.removeCallbacks(runnable)
	}

	override fun onDestroy() {
		super.onDestroy()
		val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
		locationManager.removeUpdates(this)
		handler.removeCallbacks(runnable)
	}

	private fun getQueryablesByQuery(server: Server, query: String) {
		val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
		MainScope().launch {
			val result = queryQueryables(cm, server, query)
			if (result.error != null) {
				if (result.stream != null) {
					val response = ErrorResponse.unmarshal(result.stream)
					Log.w("Results", "${result.error.statusCode}, ${response.message}")
				} else {
					Log.w(
						"Results",
						"${result.error.statusCode}, ${getString(result.error.stringResource)}"
					)
				}
				showError(result.error)
			} else {
				updateItems(unmarshallQueryablesResponse(result.stream!!)!!)
			}
		}
	}

	private fun getQueryablesByLocation(server: Server, position: PositionV1) {
		val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
		MainScope().launch {
			val result = locateQueryables(cm, server, position)
			if (result.error != null) {
				Log.e("Results.location", "$result")
				showError(result.error)
			} else {
				updateItems(unmarshallQueryablesResponse(result.stream!!)!!)
			}
		}
	}

	private fun showError(error: Error) {
		binding.resultsProgress.visibility = View.GONE
		binding.resultsRecycler.visibility = View.GONE
		binding.errorImage.visibility = View.VISIBLE
		binding.errorText.visibility = View.VISIBLE

		binding.errorText.text = getString(error.stringResource)
		binding.errorImage.setImageDrawable(AppCompatResources.getDrawable(this, error.imageResource))
	}

	private fun updateItems(queryables: List<QueryableV1>) {
		binding.resultsProgress.visibility = View.GONE
		adapter.update(queryables)
		if (queryables.isEmpty()) {
			binding.errorImage.visibility = View.VISIBLE
			binding.errorText.visibility = View.VISIBLE
			binding.resultsRecycler.visibility = View.GONE

			binding.errorText.text = getString(R.string.error_404)
			binding.errorImage.setImageDrawable(
				AppCompatResources.getDrawable(
					this,
					R.drawable.error_search
				)
			)
		} else {
			binding.resultsOverlay.visibility = View.GONE
			binding.errorImage.visibility = View.GONE
			binding.errorText.visibility = View.GONE
			binding.resultsRecycler.visibility = View.VISIBLE
		}
	}

	private suspend fun unmarshallQueryablesResponse(stream: InputStream): List<QueryableV1>? {
		return withContext(Dispatchers.IO) {
			when (val response = QueryablesResponse.unmarshal(stream)) {
				is QueryablesResponseDev -> response.queryables
				is QueryablesResponseV1 -> response.queryables
				else -> null
			}
		}
	}
}