package de.sebse.fuplanner2.ui.notification

import android.os.Bundle
import android.view.*
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 de.sebse.fuplanner2.R
import de.sebse.fuplanner2.database.AppDatabase
import de.sebse.fuplanner2.databinding.FragmentRecyclerBinding
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch


class NotificationFragment : Fragment() {

    private lateinit var viewModel: NotificationViewModel
    private lateinit var navController: NavController
    private lateinit var binding: FragmentRecyclerBinding

    init {
        setHasOptionsMenu(true)
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.notification_menu, menu)
        super.onCreateOptionsMenu(menu, inflater)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        navController = findNavController()
        val viewManager = LinearLayoutManager(context)
        val viewAdapter = NotificationAdapter(navController)
        viewModel = ViewModelProvider(this).get(NotificationViewModel::class.java)

        viewModel.text.observe(viewLifecycleOwner, Observer {
            viewAdapter.submitList(it)
        })

        return inflater.inflate(R.layout.fragment_recycler, container, false).apply {
            binding.recyclerView.apply {
                //setHasFixedSize(true)
                layoutManager = viewManager
                adapter = viewAdapter
            }
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        val id = item.itemId
        return when (id) {
            R.id.read_all -> {
                GlobalScope.launch {
                    AppDatabase.getInstance().notificationDao().setRead()
                }
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
}
