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.BuildlogType
import de.storchp.fdroidbuildstatus.utils.DrawableUtils
import de.storchp.fdroidbuildstatus.utils.PreferencesService
import javax.inject.Inject

const val BUILDLOG_TYPE_REQUEST = "buildlogTypeRequest"
const val BUILDLOG_TYPE_RESULT = "buildlogTypeResult"

@AndroidEntryPoint
class BuildlogTypeFragment : DialogFragment() {

    @Inject
    lateinit var preferencesService: PreferencesService

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val fragmentActivity = requireActivity()
        val view = requireActivity().layoutInflater.inflate(R.layout.dialog_buildlog_type, null)
        val always = view.findViewById<CheckBox>(R.id.always)
        val log = view.findViewById<ImageButton>(R.id.log)
        log.setOnClickListener {
            sendResult(
                always,
                BuildlogType.LOG
            )
        }
        log.setImageDrawable(
            DrawableUtils.getTintedDrawable(
                fragmentActivity,
                R.drawable.ic_log,
                always.currentTextColor
            )
        )
        val gz = view.findViewById<ImageButton>(R.id.gz)
        gz.setOnClickListener {
            sendResult(
                always,
                BuildlogType.GZ
            )
        }
        gz.setImageDrawable(
            DrawableUtils.getTintedDrawable(
                fragmentActivity,
                R.drawable.ic_gz,
                always.currentTextColor
            )
        )
        return MaterialAlertDialogBuilder(fragmentActivity)
            .setView(view)
            .setIcon(R.mipmap.ic_launcher)
            .setTitle(R.string.buildlog_type)
            .create()
    }

    private fun sendResult(
        always: CheckBox,
        buildlogType: BuildlogType
    ) {
        if (always.isChecked) {
            preferencesService.setBuildlogType(buildlogType)
        }
        val result = Bundle()
        result.putString(BUILDLOG_TYPE_RESULT, buildlogType.name)
        parentFragmentManager.setFragmentResult(BUILDLOG_TYPE_REQUEST, result)
        dismiss()
    }

}