package com.proyek.akhir.kodel.ui.koperasi.berita

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.proyek.akhir.kodel.R
import com.proyek.akhir.kodel.data.response.BeritaItem
import com.proyek.akhir.kodel.ui.koperasi.berita.detailBerita.AddBeritaKoperasiActivity
import com.proyek.akhir.kodel.ui.user.dashboard.DashboardViewModel
import kotlinx.android.synthetic.main.activity_berita_koperasi.*

class BeritaKoperasiActivity : AppCompatActivity() {

    private lateinit var dashboardViewModel: DashboardViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_berita_koperasi)

        rvBeritaKoperasi.setHasFixedSize(true)
        rvBeritaKoperasi.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)

        swipeBeritaKoperasi.setOnRefreshListener {
            swipeBeritaKoperasi.isRefreshing = true
            callBerita()
        }

        addBeritaKoperasi.setOnClickListener {
            startActivity(Intent(this, AddBeritaKoperasiActivity::class.java))
        }

        swipeBeritaKoperasi.isRefreshing = true
        callBerita()

    }

    private fun callBerita() {
        dashboardViewModel = ViewModelProvider(this).get(DashboardViewModel::class.java)
        dashboardViewModel.setDataBerita().observe(this, Observer { berita ->
            if (berita != null) {
                showData(berita)
            } else {

                Toast.makeText(this, "Harap Refresh!", Toast.LENGTH_SHORT).show()
            }
        })
    }

    private fun showData(berita: List<BeritaItem>) {
        rvBeritaKoperasi.adapter = BeritaKoperasiAdapter(berita)
    }
}
