package fr.iut.ouafff.ui.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.LinearLayout
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.viewpager2.widget.ViewPager2
import fr.iut.ouafff.R
import fr.iut.ouafff.data.NEW_DOG_ID
import fr.iut.ouafff.ui.fragment.DogFragment
import fr.iut.ouafff.ui.utils.DogPagerAdapter
import fr.iut.ouafff.ui.viewmodel.DogPagerViewModel


class DogPagerActivity : AppCompatActivity(), DogFragment.OnInteractionListener {

    companion object {
        private const val EXTRA_DOG_ID = "fr.iut.ouafff.extra_dog_id"

        fun getIntent(context: Context, dogId: Long) =
                Intent(context, DogPagerActivity::class.java).apply {
                    putExtra(EXTRA_DOG_ID, dogId)
                }
    }

    private val pagerAdapter = DogPagerAdapter(this)
    private val dogPagerVM by viewModels<DogPagerViewModel>()
    private lateinit var viewPager: ViewPager2

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

        setSupportActionBar(findViewById(R.id.toolbar_activity))
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        // Exemple de création d'un composant (ViewPager ici) en code
        // avec id défini en ressource (ids.xml) et injection dans la vue à l'exécution
        // … du coup pas de data binding disponible
        viewPager = ViewPager2(this)
        viewPager.id = R.id.view_pager
        findViewById<LinearLayout>(R.id.pager_layout).addView(viewPager)

        viewPager.adapter = pagerAdapter
        dogPagerVM.currentDogId = savedInstanceState?.getLong(EXTRA_DOG_ID) ?: intent.getLongExtra(
            EXTRA_DOG_ID,
            NEW_DOG_ID
        )

        dogPagerVM.dogList.observe(this) {
            pagerAdapter.submitList(it)
            var position = pagerAdapter.positionFromId(dogPagerVM.currentDogId)
            if (position == -1) position = 0
            viewPager.currentItem = position
            supportActionBar?.subtitle = getString(R.string.dogs_subtitle_format, position + 1)
        }

        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                dogPagerVM.currentDogId = pagerAdapter.dogIdAt(position)
                supportActionBar?.subtitle = getString(R.string.dogs_subtitle_format, position + 1)
            }

        })
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putLong(EXTRA_DOG_ID, dogPagerVM.currentDogId)
    }

    override fun onDogSaved() = finish()
    override fun onDogDeleted() = finish()
}

