package app.furmeet.events.system.schedule.fragments

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import app.furmeet.events.system.helper.doAsync
import app.furmeet.events.system.helper.observables.Observable
import app.furmeet.events.system.helper.observables.Observer
import app.furmeet.events.system.helper.uiThread
import app.furmeet.events.system.notification.PastNotificationsAdapter
import app.furmeet.events.system.schedule.managers.ScheduleManagerGetter
import app.furmeet.events.bff.R
import app.furmeet.events.bff.databinding.FragmentRulesListBinding

class ConventionAnnouncementsFragment : FragmentWithSafeActivity(), Observer<Any?> {
    companion object {

        fun newInstance(): Fragment {
            return ConventionAnnouncementsFragment().apply {
                arguments = Bundle()
            }
        }
    }

    lateinit var binding: FragmentRulesListBinding
    val scheduleManager = ScheduleManagerGetter[safeActivity]
    val announcements get() = scheduleManager.conventionSeries.announcements.sortedBy { -it.created.timeInMillis }

    lateinit var rootView: View

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        rootView = inflater.inflate(R.layout.fragment_rules_list, container, false)
        doAsync { configureRootView() }
        scheduleManager.addObserver(this)
        binding = FragmentRulesListBinding.bind(rootView)
        return rootView
    }

    override fun update(observable: Observable<Any?>, args: Any?) {
        configureRootView()
    }

    private fun configureRootView() {
        doAsync {
            uiThread {
                binding.apply {
                    rulesRecyclerView.adapter = PastNotificationsAdapter(announcements)
                    rulesRecyclerView.layoutManager = LinearLayoutManager(context)
                }
            }
        }
    }
}
