package org.libre.agosto.p2play.fragments

import android.os.AsyncTask
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import org.libre.agosto.p2play.adapters.VideosAdapter
import org.libre.agosto.p2play.ajax.Videos
import org.libre.agosto.p2play.databinding.FragmentChannelVideosBinding
import org.libre.agosto.p2play.helpers.getViewManager
import org.libre.agosto.p2play.models.VideoModel

private const val ARG_PARAM1 = "accountId"

class AccountVideosFragment : Fragment() {
    private var _binding: FragmentChannelVideosBinding? = null
    private val binding get() = _binding!!

    private var accountId: String? = "agosto182"
    private val videosService = Videos()

    private lateinit var viewManager: RecyclerView.LayoutManager

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            accountId = it.getString(ARG_PARAM1, accountId)
        }

        viewManager = getViewManager(this.requireContext(), resources)
    }

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

    override fun onResume() {
        super.onResume()
        getVideos()
    }

    private fun getVideos() {
        AsyncTask.execute {
            val videos = videosService.accountVideos(this.accountId!!, 0)
            activity?.runOnUiThread {
                initRecycler(videos)
            }
        }
    }

    private fun initRecycler(data: ArrayList<VideoModel>) {
        // val data = arrayListOf<VideoModel>()
        val viewAdapter = VideosAdapter(data)

        binding.videosList.apply {
            // use this setting to improve performance if you know that changes
            // in content do not change the layout size of the RecyclerView
            setHasFixedSize(true)

            // use a linear layout manager
            layoutManager = viewManager

            // specify an viewAdapter (see also next example)
            adapter = viewAdapter
        }
    }

    companion object {

        @JvmStatic
        fun newInstance(param1: String) =
            AccountVideosFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                }
            }
    }
}