package de.storchp.fdroidbuildstatus

import android.app.Dialog
import android.content.Context
import android.content.res.TypedArray
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import de.storchp.fdroidbuildstatus.databinding.ActivityLegendBinding
import de.storchp.fdroidbuildstatus.databinding.ItemLegendBinding
import de.storchp.fdroidbuildstatus.utils.DrawableUtils

class LegendFragment : DialogFragment() {
    private lateinit var binding: ActivityLegendBinding
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        binding = ActivityLegendBinding.inflate(
            layoutInflater, null, false
        )
        binding.iconsList.adapter = LegendAdapter(
            resources.obtainTypedArray(R.array.icons),
            resources.getStringArray(R.array.icon_labels),
            requireContext(),
        )
        return MaterialAlertDialogBuilder(requireActivity())
            .setIcon(R.mipmap.ic_launcher)
            .setTitle(R.string.legend_title)
            .setPositiveButton(android.R.string.ok, null)
            .setView(binding.root)
            .create()
    }

    class LegendAdapter(
        private val icons: TypedArray,
        private val labels: Array<String>,
        private val context: Context,
    ) : BaseAdapter() {
        override fun getCount(): Int {
            return icons.length()
        }

        override fun getItem(position: Int): Any {
            return icons.getDrawable(position)!!
        }

        override fun getItemId(position: Int): Long {
            return position.toLong()
        }

        override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
            var rowView = convertView
            val binding: ItemLegendBinding
            if (rowView == null) {
                binding = ItemLegendBinding.inflate(LayoutInflater.from(context), parent, false)
                rowView = binding.root
                rowView.tag = binding
            } else {
                binding = rowView.tag as ItemLegendBinding
            }
            binding.legendItem.text = labels[position]
            DrawableUtils.setCompoundDrawablesLeft(
                binding.legendItem,
                icons.getDrawable(position),
                binding.legendItem.currentTextColor
            )
            return rowView
        }
    }
}