package org.mosad.teapod.ui.activity.player.fragment

import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.ViewModelProvider
import kotlinx.coroutines.runBlocking
import org.mosad.teapod.R
import org.mosad.teapod.databinding.PlayerEpisodesListBinding
import org.mosad.teapod.ui.activity.player.PlayerViewModel
import org.mosad.teapod.util.adapter.EpisodeItemAdapter
import org.mosad.teapod.util.hideBars

class EpisodeListDialogFragment : DialogFragment()  {

    private lateinit var model: PlayerViewModel
    private lateinit var binding: PlayerEpisodesListBinding

    companion object {
        const val TAG = "LanguageSettingsDialogFragment"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NO_TITLE, R.style.FullScreenDialogStyle)
        model = ViewModelProvider(requireActivity())[PlayerViewModel::class.java]
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        binding = PlayerEpisodesListBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.buttonCloseEpisodesList.setOnClickListener {
            dismiss()
        }

        val adapterRecEpisodes = EpisodeItemAdapter(
            model.episodes.data,
            null,
            model.currentPlayheads,
            EpisodeItemAdapter.OnClickListener { episode ->
                dismiss()
                // TODO make this none blocking, if necessary?
                runBlocking {
                    model.setCurrentEpisode(episode.id, startPlayback = true)
                }
            },
            EpisodeItemAdapter.ViewType.PLAYER
        )

        // get the position/index of the currently playing episode
        adapterRecEpisodes.currentSelected = model.episodes.data.indexOfFirst { it.id == model.currentEpisode.id }

        binding.recyclerEpisodesPlayer.adapter = adapterRecEpisodes
        binding.recyclerEpisodesPlayer.scrollToPosition(adapterRecEpisodes.currentSelected)

        // initially hide the status and navigation bar
        hideBars(requireDialog().window, binding.root)
    }

    override fun onDismiss(dialog: DialogInterface) {
        super.onDismiss(dialog)
        model.player.play()
    }
}
