package de.storchp.fdroidbuildstatus

import android.app.Dialog
import android.os.Bundle
import android.widget.CheckBox
import android.widget.ImageButton
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.model.MetadataLinkType
import de.storchp.fdroidbuildstatus.utils.DrawableUtils
import de.storchp.fdroidbuildstatus.utils.PreferencesService
import javax.inject.Inject

const val METADATA_LINK_TYPE_REQUEST = "metadataLinkTypeRequest"
const val METADATA_LINK_TYPE_RESULT = "metadataLinkTypeResult"

@AndroidEntryPoint
class MetadataLinkTypeFragment : DialogFragment() {

    @Inject
    lateinit var preferencesService: PreferencesService

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val fragmentActivity = requireActivity()
        val view =
            requireActivity().layoutInflater.inflate(R.layout.dialog_metadata_link_type, null)
        val always = view.findViewById<CheckBox>(R.id.always)
        val yaml = view.findViewById<ImageButton>(R.id.yaml)
        yaml.setOnClickListener {
            sendResult(
                always,
                MetadataLinkType.YAML
            )
        }
        yaml.setImageDrawable(
            DrawableUtils.getTintedDrawable(
                fragmentActivity,
                R.drawable.ic_yaml,
                always.currentTextColor
            )
        )
        val gitlab = view.findViewById<ImageButton>(R.id.gitlab)
        gitlab.setOnClickListener {
            sendResult(
                always,
                MetadataLinkType.GITLAB
            )
        }
        gitlab.setImageDrawable(
            DrawableUtils.getTintedDrawable(
                fragmentActivity,
                R.drawable.ic_gitlab,
                always.currentTextColor
            )
        )
        return MaterialAlertDialogBuilder(fragmentActivity)
            .setView(view)
            .setIcon(R.mipmap.ic_launcher)
            .setTitle(R.string.metadata_link_type)
            .create()
    }

    private fun sendResult(
        always: CheckBox,
        metadataLinkType: MetadataLinkType
    ) {
        if (always.isChecked) {
            preferencesService.setMetadataLinkType(metadataLinkType)
        }
        val result = Bundle()
        result.putString(METADATA_LINK_TYPE_RESULT, metadataLinkType.name)
        parentFragmentManager.setFragmentResult(METADATA_LINK_TYPE_REQUEST, result)
        dismiss()
    }

}