package bou.amine.apps.readerforselfossv2.android

import android.content.Intent
import android.content.res.ColorStateList
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import bou.amine.apps.readerforselfossv2.android.adapters.SourcesListAdapter
import bou.amine.apps.readerforselfossv2.android.databinding.ActivitySourcesBinding
import bou.amine.apps.readerforselfossv2.android.testing.CountingIdlingResourceSingleton
import bou.amine.apps.readerforselfossv2.model.SelfossModel
import bou.amine.apps.readerforselfossv2.repository.Repository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.kodein.di.DIAware
import org.kodein.di.android.closestDI
import org.kodein.di.instance

class SourcesActivity : AppCompatActivity(), DIAware {
    private lateinit var binding: ActivitySourcesBinding

    override val di by closestDI()
    private val repository: Repository by instance()

    override fun onCreate(savedInstanceState: Bundle?) {
        binding = ActivitySourcesBinding.inflate(layoutInflater)
        val view = binding.root

        super.onCreate(savedInstanceState)

        setContentView(view)

        setSupportActionBar(binding.toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setDisplayShowHomeEnabled(true)

        binding.fab.rippleColor = resources.getColor(R.color.colorAccentDark)
        binding.fab.backgroundTintList =
            ColorStateList.valueOf(resources.getColor(R.color.colorAccent))
    }

    override fun onStop() {
        super.onStop()
        binding.recyclerView.clearOnScrollListeners()
    }

    override fun onResume() {
        super.onResume()
        val mLayoutManager = LinearLayoutManager(this)

        var items: ArrayList<SelfossModel.SourceDetail>

        binding.recyclerView.setHasFixedSize(true)
        binding.recyclerView.layoutManager = mLayoutManager

        CountingIdlingResourceSingleton.increment()
        CoroutineScope(Dispatchers.Main).launch {
            val response = repository.getSourcesDetails()
            if (response.isNotEmpty()) {
                items = response
                val mAdapter =
                    SourcesListAdapter(
                        this@SourcesActivity,
                        items,
                    )
                binding.recyclerView.adapter = mAdapter
                mAdapter.notifyDataSetChanged()
            } else {
                Toast.makeText(
                    this@SourcesActivity,
                    R.string.cant_get_sources,
                    Toast.LENGTH_SHORT,
                ).show()
            }
            CountingIdlingResourceSingleton.decrement()
        }

        binding.fab.setOnClickListener {
            startActivity(Intent(this@SourcesActivity, UpsertSourceActivity::class.java))
        }
    }
}