package com.mime.dualscreenview.dialog

import android.R
import android.content.Context
import android.content.DialogInterface
import android.widget.ArrayAdapter
import androidx.appcompat.app.AlertDialog
import com.mime.dualscreenview.data.model.BookPageInfo

object DefaultList {
    fun showDefaultList(context: Context, title : String, items : Collection<BookPageInfo>, firstPosition : Int, choosedTitle : (Int)->String, chooedPositive : (Int)->Unit, saveCalback : (Int)->Unit ) {
        val builderSingle: AlertDialog.Builder = AlertDialog.Builder(context)
        builderSingle.setTitle(title)
        val arrayAdapter =
            ArrayAdapter<String>(context, R.layout.select_dialog_singlechoice)
        for (item in items) {
            arrayAdapter.add(item.getTitleItem())
        }
        builderSingle.setNeutralButton("전체 저장")  { dialog, which ->
            saveCalback.invoke(-1)
            dialog.dismiss()
        }
        builderSingle.setNegativeButton("닫기",
            DialogInterface.OnClickListener { dialog, which ->
                dialog.dismiss() })
        builderSingle.setAdapter(arrayAdapter,
            DialogInterface.OnClickListener { dialog, position ->
                val strName = arrayAdapter.getItem(position)
                val builderInner: AlertDialog.Builder = AlertDialog.Builder(context)
                builderInner.setMessage(strName)
                builderInner.setTitle(choosedTitle.invoke(position))
                builderInner.setNegativeButton("닫기") { dialog, which ->

                }
//                builderInner.setNeutralButton("자동 저장") { dialog, which ->
//                    saveCalback.invoke(position)
//                }
                builderInner.setPositiveButton("이동"){ dialog, which ->
                    chooedPositive.invoke(position)
                    dialog.dismiss()
                }
                builderInner.show().apply {
                    DialogManager.add(this)
                }
            })
        builderSingle.create()?.apply{
            setOnShowListener { d->
                (d as? AlertDialog)?.let{
                    it.listView?.setSelection(firstPosition)
                }
            }
            DialogManager.add(this)
        }?.show()
    }
}