package de.sebse.fuplanner2.ui.details_announcements

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.NavController
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.work.workDataOf
import de.sebse.fuplanner2.R
import de.sebse.fuplanner2.auth.AppAccounts
import de.sebse.fuplanner2.databinding.FragmentRefreshRecyclerBinding
import de.sebse.fuplanner2.utils.console
import de.sebse.fuplanner2.utils.enqueueOneTimeWork
import de.sebse.fuplanner2.worker.AbstractAccountWorker.Companion.KEY_ACCOUNT_NAME
import de.sebse.fuplanner2.worker.AbstractAccountWorker.Companion.KEY_COURSE_ID
import de.sebse.fuplanner2.worker.AnnouncementWorker

class AnnouncementsFragment : Fragment() {

    private var title: String = ""
    private val args: AnnouncementsFragmentArgs by navArgs()
    private val announcementsViewModel: AnnouncementsViewModel by viewModels { AnnouncementsViewModelFactory(args.courseId) }
    private lateinit var navController: NavController
    private lateinit var binding: FragmentRefreshRecyclerBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val viewManager = LinearLayoutManager(context)
        val viewAdapter = AnnouncementsAdapter()
        return inflater.inflate(R.layout.fragment_refresh_recycler, container, false).apply {
            console.log(findViewById(R.id.recycler_view), binding.recyclerView)
            binding.recyclerView.apply {
                setHasFixedSize(true)

                layoutManager = viewManager
                adapter = viewAdapter
            }
            binding.swipeRefreshLayout.setOnRefreshListener {
                enqueueOneTimeWork<AnnouncementWorker>(context.applicationContext) {
                    it.setInputData(workDataOf(
                        KEY_ACCOUNT_NAME to AppAccounts.getInstance().selectedAccount?.name,
                        KEY_COURSE_ID to args.courseId
                    ))
                }.observe(viewLifecycleOwner, Observer {
                    if (it.state.isFinished)
                        binding.swipeRefreshLayout.isRefreshing = false
                })
            }
            announcementsViewModel.events.observe(viewLifecycleOwner, Observer {
                viewAdapter.submitList(it)
                this@AnnouncementsFragment.title = args.title
            })
            navController = findNavController()
        }
    }
}