package com.divya.animaltap.ui

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.divya.animaltap.R
import com.divya.animaltap.model.Animal
import com.divya.animaltap.util.SoundPlayer

import com.divya.animaltap.data.AnimalRepository
import com.google.android.material.floatingactionbutton.FloatingActionButton

class MainActivity : AppCompatActivity() {

    private lateinit var soundPlayer: SoundPlayer

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

        soundPlayer = SoundPlayer(this)

        val animals = AnimalRepository.animals
        val recyclerView = findViewById<RecyclerView>(R.id.recycler_view)
        
        // Use 2 columns nicely spaced
        recyclerView.layoutManager = GridLayoutManager(this, 2)
        recyclerView.adapter = AnimalAdapter(animals) { animal ->
            launchDetail(animal)
        }


        // Surprise Me Button
        val fabSurprise = findViewById<FloatingActionButton>(R.id.fab_surprise)
        fabSurprise.setOnClickListener {
            val randomAnimal = animals.random()
            
            // Spin animation!
            fabSurprise.animate().rotationBy(360f).setDuration(300).withEndAction {
                android.widget.Toast.makeText(this, "Surprise! 🎁 Here is your animal!", android.widget.Toast.LENGTH_SHORT).show()
                launchDetail(randomAnimal)
            }.start()
        }
    }

    private fun launchDetail(animal: Animal) {
        val intent = AnimalDetailActivity.newIntent(
            this,
            animal.id,
            animal.nameRes,
            animal.imageRes,
            animal.colorRes,
            animal.nameSoundRes,
            animal.animalSoundRes
        )
        startActivity(intent)
    }

    private fun playAnimalSound(animal: Animal) {
        soundPlayer.playAnimalSound(animal.nameSoundRes, animal.animalSoundRes)
    }

    override fun onDestroy() {
        super.onDestroy()
        soundPlayer.stop()
    }
}
