package de.sebse.fuplanner2.ui.courses

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.NavController
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.workDataOf
import de.sebse.fuplanner2.R
import de.sebse.fuplanner2.auth.AppAccounts
import de.sebse.fuplanner2.database.Course
import de.sebse.fuplanner2.databinding.ActivityMainBinding
import de.sebse.fuplanner2.databinding.FragmentRefreshRecyclerBinding
import de.sebse.fuplanner2.worker.AbstractAccountWorker.Companion.KEY_ACCOUNT_NAME
import de.sebse.fuplanner2.worker.CourseWorker

class CoursesFragment : Fragment() {

    private lateinit var coursesViewModel: CoursesViewModel
    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 = CoursesAdapter(this::onClick)
        coursesViewModel = ViewModelProvider(this).get(CoursesViewModel::class.java)
        binding = FragmentRefreshRecyclerBinding.inflate(inflater, container, false)
        return inflater.inflate(R.layout.fragment_refresh_recycler, container, false).apply {
            binding.recyclerView.apply {
                //setHasFixedSize(true)
                layoutManager = viewManager
                adapter = viewAdapter
            }
            binding.swipeRefreshLayout.setOnRefreshListener {
                val work = OneTimeWorkRequestBuilder<CourseWorker>()
                    .setInputData(workDataOf(
                        KEY_ACCOUNT_NAME to AppAccounts.getInstance().selectedAccount?.name
                    ))
                    .build()
                WorkManager.getInstance(context.applicationContext)
                    .enqueue(work)
                WorkManager.getInstance(context.applicationContext)
                    .getWorkInfoByIdLiveData(work.id)
                    .observe(viewLifecycleOwner, {
                        if (it.state.isFinished)
                            binding.swipeRefreshLayout.isRefreshing = false
                    })
            }
            coursesViewModel.text.observe(viewLifecycleOwner, Observer {
                viewAdapter.dataset = it
            })
            navController = findNavController()
        }
    }

    private fun onClick(course: Course) {
        course.uid?.let {
            navController.navigate(CoursesFragmentDirections.actionNavHomeToCourseDetails(it, course.title))
        }
    }
}
