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.ChannelAdapter
import org.libre.agosto.p2play.ajax.Accounts
import org.libre.agosto.p2play.databinding.FragmentChannelsBinding
import org.libre.agosto.p2play.helpers.getViewManager
import org.libre.agosto.p2play.models.ChannelModel

private const val ARG_PARAM1 = "accountId"

class AccountChannelsFragment : Fragment() {
    private var _binding: FragmentChannelsBinding? = null
    private val binding get() = _binding!!
    private var accountId: String? = null

    private val client = Accounts()

    private lateinit var viewManager: RecyclerView.LayoutManager

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

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentChannelsBinding.inflate(inflater, container, false)

        return binding.root
    }

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

    private fun getChannels() {
        AsyncTask.execute {
            val channels = client.getChannels(this.accountId!!)
            requireActivity().runOnUiThread {
                initRecycler(channels)
            }
        }
    }

    private fun initRecycler(data: ArrayList<ChannelModel>) {
        val viewAdapter = ChannelAdapter(data)

        binding.channelList.apply {
            viewAdapter.parent = requireActivity()
            setHasFixedSize(true)

            // use a linear layout manager
            layoutManager = viewManager

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

    companion object {
        @JvmStatic
        fun newInstance(accountId: String) =
            AccountChannelsFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, accountId)
                }
            }
    }
}