package de.storchp.fdroidbuildstatus

import android.annotation.SuppressLint
import android.app.Dialog
import android.os.Bundle
import android.text.method.LinkMovementMethod
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import dagger.hilt.android.AndroidEntryPoint
import de.storchp.fdroidbuildstatus.adapter.db.DbAdapter
import de.storchp.fdroidbuildstatus.databinding.ActivityAboutBinding
import de.storchp.fdroidbuildstatus.model.BuildCycle
import de.storchp.fdroidbuildstatus.model.BuildRun
import de.storchp.fdroidbuildstatus.utils.FormatUtils
import javax.inject.Inject

@AndroidEntryPoint
class AppInfoFragment : DialogFragment() {

    @Inject
    lateinit var dbAdapter: DbAdapter

    private lateinit var binding: ActivityAboutBinding

    @SuppressLint("SetTextI18n")
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val fragmentActivity = requireActivity()
        val builder = MaterialAlertDialogBuilder(fragmentActivity)
            .setIcon(R.mipmap.ic_launcher)
            .setTitle(R.string.app_info_title)
            .setPositiveButton(android.R.string.ok, null)

        binding = ActivityAboutBinding.inflate(layoutInflater, null, false).apply {
            aboutVersionText.text = "${BuildConfig.VERSION_NAME} (${BuildConfig.VERSION_CODE})"
            aboutInfo.movementMethod = LinkMovementMethod.getInstance()
            val buildRuns = dbAdapter.loadBuildRuns()
            aboutLastUpdateBuildText.text = getLastUpdate(buildRuns, BuildCycle.BUILD)
            aboutLastUpdateRunningText.text = getLastUpdate(buildRuns, BuildCycle.RUNNING)
        }

        builder.setView(binding.root)
        return builder.create()
    }

    private fun getLastUpdate(buildRuns: Map<BuildCycle, BuildRun>, runType: BuildCycle): String {
        return buildRuns[runType]?.let {
            it.lastUpdated.time.let { it1 -> FormatUtils.formatShortDateTime(it1) }
        } ?: ""
    }
}