package org.freedesktop.gstreamer.examples.webrtcsrc

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.launch
import org.freedesktop.gstreamer.examples.webrtcsrc.adapter.ProducerTableRowAdapter
import org.freedesktop.gstreamer.examples.webrtcsrc.databinding.ProducerListFragmentBinding
import org.freedesktop.gstreamer.examples.webrtcsrc.io.SignallerClient
import org.freedesktop.gstreamer.examples.webrtcsrc.model.Peer

class ProducerListFragment : Fragment() {
    private var _binding: ProducerListFragmentBinding? = null
    private val binding get() = _binding!!
    private lateinit var recyclerView : RecyclerView
    private lateinit var producerTableRowAdapter : ProducerTableRowAdapter

    override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View {

        _binding = ProducerListFragmentBinding.inflate(inflater, container, false)

        recyclerView = binding.recyclerViewTableProducer
        producerTableRowAdapter = ProducerTableRowAdapter(listOf<Peer>()) { producer ->
            // ProducerListFragmentDirections is generated by the androidx.navigation.safeargs plugin
            // from declarations in res/navigation/nav_graph.xml
            val action = ProducerListFragmentDirections.startConsumer(producer.id)
            findNavController().navigate(action)
        }

        recyclerView.layoutManager = LinearLayoutManager(activity)
        recyclerView.adapter = producerTableRowAdapter

        return binding.root
    }

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

        binding.producerListRefreshButton.setOnClickListener {
            viewLifecycleOwner.lifecycleScope.launch {
                retrieve()
            }
        }
    }

    override fun onResume() {
        viewLifecycleOwner.lifecycleScope.launch {
            retrieve()
        }

        super.onResume()
    }

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

    private suspend fun retrieve() {
        val prefs = PreferenceManager.getDefaultSharedPreferences(requireActivity())
        val signallerUri = prefs.getString("signaller_uri", getString(R.string.signaller_uri))!!

        SignallerClient(signallerUri)
            .retrieveProducers()
            .onSuccess { list ->
                if (list.isNotEmpty()) {
                    producerTableRowAdapter.setProducers(list)
                } else {
                    producerTableRowAdapter.setProducers(listOf<Peer>())
                    Snackbar.make(binding.root, getString(R.string.no_producers_message),
                        Snackbar.LENGTH_LONG).show()
                }
            }
            .onFailure { e ->
                producerTableRowAdapter.setProducers(listOf<Peer>())
                Snackbar.make(binding.root, String.format(getString(R.string.producer_retrieval_error),e.localizedMessage),
                    Snackbar.LENGTH_LONG).show()
            }
    }
}