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

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.KuponItem
import com.proyek.akhir.kodel.ui.koperasi.kupon.addKupon.TambahKuponActivity
import kotlinx.android.synthetic.main.activity_kupon_koperasi.*

class KuponKoperasiActivity : AppCompatActivity() {

    lateinit var viewModelKuponKoperasi: KuponViewModel

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

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

        swipeKuponKoperasi.setOnRefreshListener {
            swipeKuponKoperasi.isRefreshing = true
            callKupon()
            swipeKuponKoperasi.isRefreshing = false
        }

        addKuponKoperasi.setOnClickListener {
            startActivity(Intent(this, TambahKuponActivity::class.java))
        }

        swipeKuponKoperasi.isRefreshing = true
        callKupon()
        swipeKuponKoperasi.isRefreshing = false
    }


    private fun callKupon() {
        viewModelKuponKoperasi = ViewModelProvider(this).get(KuponViewModel::class.java)
        viewModelKuponKoperasi.setDataKupon().observe(this, Observer { kupon ->
            if (kupon != null) {
                showData(kupon)
            } else {
                Toast.makeText(this, "Internet Lemah!", Toast.LENGTH_SHORT).show()
            }
        })
    }

    private fun showData(kupon: List<KuponItem>) {
        rvKuponKoperasi.adapter = KuponAdapter(kupon)
    }
}
