// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: GPL-3.0-or-later

package xyz.apiote.bimba.czwek.settings

import android.content.Context
import android.os.Bundle
import android.text.format.DateUtils
import android.view.View
import android.view.ViewGroup
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updateLayoutParams
import androidx.core.view.updatePadding
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.PreferenceManager
import androidx.preference.SwitchPreferenceCompat
import androidx.work.ExistingWorkPolicy
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.OutOfQuotaPolicy
import androidx.work.WorkInfo
import androidx.work.WorkManager
import xyz.apiote.bimba.czwek.R
import java.util.concurrent.ExecutionException


class SettingsActivity : AppCompatActivity() {

	override fun onCreate(savedInstanceState: Bundle?) {
		enableEdgeToEdge()
		super.onCreate(savedInstanceState)
		setContentView(R.layout.settings_activity)
		if (savedInstanceState == null) {
			supportFragmentManager
				.beginTransaction()
				.replace(R.id.settings, SettingsFragment())
				.commit()
		}
		supportActionBar?.setDisplayHomeAsUpEnabled(true)

		val root = findViewById<View>(R.id.settings)

		ViewCompat.setOnApplyWindowInsetsListener(root) { v, windowInsets ->
			val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars())
			v.updatePadding(left = windowInsets.displayCutout?.safeInsetLeft?.takeIf { it > 0 } ?: insets.left)
			v.updatePadding(right = windowInsets.displayCutout?.safeInsetRight?.takeIf { it > 0 } ?: insets.right)
			v.updateLayoutParams<ViewGroup.MarginLayoutParams> {
				topMargin = insets.top
			}
			windowInsets
		}
	}

	class SettingsFragment : PreferenceFragmentCompat() {
		override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
			setPreferencesFromResource(R.xml.root_preferences, rootKey)

			findPreference<Preference>("download_cities_list")?.setOnPreferenceClickListener {
				val request = OneTimeWorkRequestBuilder<DownloadCitiesWorker>()
					.setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)
					.build()
				WorkManager.getInstance(requireContext())
					.enqueueUniqueWork("download_cities", ExistingWorkPolicy.KEEP, request)
				findPreference<Preference>("download_cities_list")?.isEnabled = false
				true
			}

			if (isWorkScheduled(requireContext(), "download_cities")) {
				findPreference<Preference>("download_cities_list")?.isEnabled = false
			}

			val citiesLastUpdate = PreferenceManager.getDefaultSharedPreferences(requireContext())
				.getLong(DownloadCitiesWorker.LAST_UPDATE_KEY, -1)
			if (citiesLastUpdate > 0) {
				val lastUpdateTime = DateUtils.getRelativeDateTimeString(
					context,
					citiesLastUpdate * DateUtils.SECOND_IN_MILLIS,
					DateUtils.DAY_IN_MILLIS,
					DateUtils.WEEK_IN_MILLIS,
					0
				)

				findPreference<SwitchPreferenceCompat>("autoupdate_cities_list")?.summary =
					getString(R.string.last_update, lastUpdateTime)
			}
		}

		private fun isWorkScheduled(context: Context, name: String): Boolean {
			val instance = WorkManager.getInstance(context)
			val statuses = instance.getWorkInfosForUniqueWork(name)
			try {
				var running = false
				val workInfoList = statuses.get()
				for (workInfo in workInfoList) {
					val state: WorkInfo.State = workInfo.state
					running = (state == WorkInfo.State.RUNNING) or (state == WorkInfo.State.ENQUEUED)
				}
				return running
			} catch (e: ExecutionException) {
				e.printStackTrace()
				return false
			} catch (e: InterruptedException) {
				e.printStackTrace()
				return false
			}
		}
	}
}