package com.github.libretube.ui.fragments

import android.os.Bundle
import android.view.View
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.github.libretube.R
import com.github.libretube.databinding.FragmentMyPlaylistsBinding
import com.github.libretube.enums.PlaylistType
import com.github.libretube.extensions.ceilHalf
import com.github.libretube.repo.LocalPlaylistsRepository
import com.github.libretube.ui.adapters.PlaylistsAdapter
import com.github.libretube.ui.base.DynamicLayoutManagerFragment
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MyPlaylistsFragment : DynamicLayoutManagerFragment(R.layout.fragment_my_playlists) {
    private var _binding: FragmentMyPlaylistsBinding? = null
    private val binding get() = _binding!!

    private val playlistsAdapter = PlaylistsAdapter(PlaylistType.LOCAL)

    override fun setLayoutManagers(gridItems: Int) {
        _binding?.playlistsRecView?.layoutManager = GridLayoutManager(context, gridItems.ceilHalf())
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        _binding = FragmentMyPlaylistsBinding.bind(view)
        super.onViewCreated(view, savedInstanceState)

        binding.playlistsRecView.adapter = playlistsAdapter
        binding.playlistRefresh.setOnRefreshListener { fetchPlaylists() }

        fetchPlaylists()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    private fun fetchPlaylists() {
        binding.playlistRefresh.isRefreshing = true
        lifecycleScope.launch {
            val playlists = try {
                withContext(Dispatchers.IO) {
                    LocalPlaylistsRepository().getPlaylists()
                }
            } catch (e: Exception) {
                binding.playlistRefresh.isRefreshing = false
                binding.nothingHere.isVisible = true
                return@launch
            }

            binding.playlistRefresh.isRefreshing = false
            binding.nothingHere.isVisible = playlists.isEmpty()
            binding.playlistsRecView.isVisible = playlists.isNotEmpty()
            playlistsAdapter.submitList(playlists)
        }
    }
}
