package fr.plnech.dunbar.ui

import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.snackbar.Snackbar
import fr.plnech.dunbar.R
import fr.plnech.dunbar.dummy.DummyContent
import fr.plnech.dunbar.model.Friend
import fr.plnech.dunbar.plural
import kotlinx.android.synthetic.main.activity_friends_list.*
import kotlinx.android.synthetic.main.friend_list.*

class FriendListActivity : AppCompatActivity() {

    /**
     * Whether or not the activity is in two-pane mode, i.e. running on a tablet
     * device.
     */
    private var twoPane: Boolean = false

    private var friends = listOf<Friend>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_friends_list)
        setSupportActionBar(toolbar)
        toolbar.title = title

        fab.setOnClickListener { view ->
            Snackbar.make(view, "Replace with your own stuff", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show()
        }

        if (friend_detail_container != null) {
            // The detail container view will be present only in the
            // large-screen layouts (res/values-w900dp).
            // If this view is present, then the
            // activity should be in two-pane mode.
            twoPane = true
        }

        reloadFriends()
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_main, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        return when (item.itemId) {
            R.id.action_settings -> true
            R.id.action_contacts -> {
                startActivity(Intent(this, ContactsActivity::class.java))
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    private fun reloadFriends() {
        println("Reload")
        friends = DummyContent.ITEMS // FIXME: Persistence
        displayFriends()
//        fetchMessages()
    }

    private fun displayFriends() {
        println("displayF")
        val adapter = FriendsPanesViewAdapter(this, friends, twoPane)
        val nbFriends = adapter.itemCount

        friend_list.layoutManager = LinearLayoutManager(this)
        friend_list.setHasFixedSize(true)
        friend_list.adapter = adapter
        val welcomeFriends =
            getString(R.string.text_welcome).format(nbFriends, "friend".plural(nbFriends))
        title = welcomeFriends
        println("Welcome: $welcomeFriends")
    }
}
