package app.furmeet.events.brasilfurfest.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 com.adlerosn.brasilfurfest.R
import app.furmeet.events.brasilfurfest.helper.ActivitiesForFragments
import app.furmeet.events.brasilfurfest.helper.observables.Observable
import app.furmeet.events.brasilfurfest.helper.observables.Observer
import app.furmeet.events.brasilfurfest.notification.PastNotificationsAdapter
import app.furmeet.events.brasilfurfest.schedule.managers.ScheduleManagerGetter
import kotlinx.android.synthetic.main.fragment_rules_list.view.*
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread

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

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

    private val safeActivity = ActivitiesForFragments["ScheduleActivity"]!!

    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)
        return rootView
    }

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

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