package xyz.apiote.bimba.czwek.settings.feeds

import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.content.edit
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import xyz.apiote.bimba.czwek.api.ErrorResponse
import xyz.apiote.bimba.czwek.api.FeedInfoV1
import xyz.apiote.bimba.czwek.api.FeedsResponse
import xyz.apiote.bimba.czwek.api.FeedsResponseDev
import xyz.apiote.bimba.czwek.api.FeedsResponseV1
import xyz.apiote.bimba.czwek.api.Server
import xyz.apiote.bimba.czwek.api.getFeeds
import xyz.apiote.bimba.czwek.dashboard.MainActivity
import xyz.apiote.bimba.czwek.databinding.ActivityFeedChooserBinding

class FeedChooserActivity : AppCompatActivity() {
	private var _binding: ActivityFeedChooserBinding? = null
	private val binding get() = _binding!!

	private lateinit var adapter: BimbaFeedInfoAdapter

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

		setUpRecycler()
		getServer()

		binding.button.setOnClickListener {
			moveOn()
		}
	}

	private fun setUpRecycler() {
		binding.resultsRecycler.layoutManager = LinearLayoutManager(this)
		adapter = BimbaFeedInfoAdapter(layoutInflater, listOf(), this) {
			FeedBottomSheet(it).show(supportFragmentManager, FeedBottomSheet.TAG)
		}
		binding.resultsRecycler.adapter = adapter
	}

	private fun getServer() {
		binding.progress.visibility = View.VISIBLE
		binding.resultsRecycler.visibility = View.GONE

		MainScope().launch {
			val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
			Log.i("FeedChooser", "${Server.get(this@FeedChooserActivity)}")
			val result = getFeeds(cm, Server.get(this@FeedChooserActivity))
			if (result.error != null) {
				showError(result.error.imageResource, result.error.stringResource)
				if (result.stream != null) {
					val response = withContext(Dispatchers.IO) {ErrorResponse.unmarshal(result.stream)}
					Log.w("FeedChooser", "${result.error.statusCode}, ${response.message}")
				} else {
					Log.w(
						"FeedChooser",
						"${result.error.statusCode}, ${getString(result.error.stringResource)}"
					)
				}
				return@launch
			}
			val feeds = when (val response = withContext(Dispatchers.IO) {FeedsResponse.unmarshal(result.stream!!)}) {
				is FeedsResponseDev -> response.feeds
				is FeedsResponseV1 -> response.feeds
				else -> null
			}
			updateItems(feeds!!)
		}
	}

	private fun moveOn() {
		val preferences = getSharedPreferences("shp", MODE_PRIVATE)
		preferences.edit(true) {
			putBoolean("inFeedsTransaction", false)
		}
		if (preferences.getBoolean("firstRun", true)) {
			val intent = Intent(this, MainActivity::class.java)
			startActivity(intent)
		}
		finish()
	}

	private fun showError(image: Int, text: Int) {
		binding.progress.visibility = View.GONE
		binding.resultsRecycler.visibility = View.GONE
		binding.errorImage.apply {
			visibility = View.VISIBLE
			setImageDrawable(AppCompatResources.getDrawable(this@FeedChooserActivity, image))
		}
		binding.errorText.apply {
			visibility = View.VISIBLE
			setText(text)
		}

	}

	private fun updateItems(feeds: List<FeedInfoV1>) {
		binding.feedsOverlay.visibility = View.GONE
		binding.resultsRecycler.visibility = View.VISIBLE
		binding.button.visibility = View.VISIBLE
		adapter.update(feeds)
	}
}