package de.storchp.fdroidbuildstatus

import android.app.Dialog
import android.os.Bundle
import android.widget.Toast
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.ApiResponse
import de.storchp.fdroidbuildstatus.adapter.fdroid.FdroidClient
import de.storchp.fdroidbuildstatus.adapter.fdroid.WebsiteBuildStatus
import de.storchp.fdroidbuildstatus.databinding.ActivityWebsiteBuildStatusBinding
import de.storchp.fdroidbuildstatus.utils.FormatUtils
import javax.inject.Inject

@AndroidEntryPoint
class WebsiteBuildStatusFragment : DialogFragment() {

    @Inject
    lateinit var fdroidClient: FdroidClient

    private lateinit var binding: ActivityWebsiteBuildStatusBinding
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val fragmentActivity = requireActivity()
        val builder = MaterialAlertDialogBuilder(fragmentActivity)
        builder.setIcon(R.mipmap.ic_launcher)
            .setTitle(R.string.action_website_build_status)
            .setPositiveButton(android.R.string.ok, null)
        binding = ActivityWebsiteBuildStatusBinding.inflate(
            layoutInflater, null, false
        )
        fdroidClient.getWebsiteBuildStatus { response: ApiResponse<WebsiteBuildStatus?> ->
            val websiteBuildStatus = response.value()
            if (response.isSuccess) {
                binding.websiteBuildStatusStartTimestampText.text =
                    FormatUtils.formatShortDateTime(
                        websiteBuildStatus!!.startTimestamp
                    )
                if (websiteBuildStatus.endTimestamp == 0L) {
                    binding.websiteBuildStatusEndTimestampText.setText(R.string.website_build_status_running)
                } else {
                    binding.websiteBuildStatusEndTimestampText.text =
                        FormatUtils.formatShortDateTime(
                            websiteBuildStatus.endTimestamp
                        )
                }
            } else {
                val context = context
                if (context != null) {
                    Toast.makeText(
                        context,
                        getString(
                            R.string.load_website_build_status_failed,
                            response.errorMessage()
                        ),
                        Toast.LENGTH_LONG
                    ).show()
                }
            }
        }
        builder.setView(binding.root)
        return builder.create()
    }

}