package fr.plnech.dunbar.ui

import android.os.Bundle
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NavUtils
import androidx.core.app.NotificationManagerCompat
import androidx.recyclerview.widget.LinearLayoutManager
import fr.plnech.dunbar.R
import fr.plnech.dunbar.data.Messages
import fr.plnech.dunbar.fetchContacts
import fr.plnech.dunbar.model.Friend
import fr.plnech.dunbar.notif.FriendReminder
import kotlinx.android.synthetic.main.activity_contacts.*
import kotlinx.android.synthetic.main.content_contacts.*
import java.util.*


class ContactsActivity : AppCompatActivity() {

    private lateinit var messages: Messages
    private var contacts = listOf<Friend>()

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

//        messages = Messages(applicationContext)

        fab.setOnClickListener { view ->
            reloadContacts()
            notifyFriend()
        }

        // Show the Up button in the action bar.
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        reloadContacts()
        notifyFriend()
    }

    private fun notifyFriend() {
        val idNotification = 0
        val notRecentlyTalked = contacts.filter {
            it.lastDate != null && (Date().time - it.lastDate!!.time) > 1 * 60 * 60 * 1000
        }
        println("${notRecentlyTalked.size} good old contacts I could talk to.")
        val friend = notRecentlyTalked.minBy { it.timesContacted }


        friend?.let {
            with(NotificationManagerCompat.from(this)) {
                val notification =
                    FriendReminder(applicationContext).createNotification(
                        friend,
                        this@ContactsActivity
                    )
                notification?.let {
                    notify(idNotification, notification)
                }
            }
        }
    }

    override fun onOptionsItemSelected(item: MenuItem) =
        when (item.itemId) {
            android.R.id.home -> {
                NavUtils.navigateUpFromSameTask(this)
                true
            }
            else -> super.onOptionsItemSelected(item)
        }

    private fun reloadContacts() {
        contacts = fetchContacts()
        displayContacts()
    }

    private fun displayContacts() {
        val adapter = FriendsAdapter(contacts)
        val nbFriends = adapter.itemCount

        contactsList.layoutManager = LinearLayoutManager(this)
        contactsList.setHasFixedSize(true)
        contactsList.adapter = adapter
        contactsTitle.text = getString(R.string.text_contacts).format(nbFriends)
    }
}
