package org.jdc.sample.ux.sample

import android.R
import android.arch.lifecycle.Observer
import android.os.Bundle
import android.util.Log
import android.view.MenuItem
import kotlinx.android.synthetic.main.activity_sample.*
import kotlinx.android.synthetic.main.toolbar_actionbar.*
import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.experimental.run
import org.jdc.sample.R.layout.activity_sample
import org.jdc.sample.datasource.database.main.individual.Individual
import org.jdc.sample.datasource.database.main.individual.IndividualDao
import org.jdc.sample.inject.Injector
import org.jdc.sample.ui.activity.BaseActivity
import javax.inject.Inject

class SampleActivity : BaseActivity() {

    @Inject
    lateinit var individualDao: IndividualDao

    init {
        Injector.get().inject(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(activity_sample)

        setSupportActionBar(mainToolbar)
        enableActionBarBackArrow(true)

        testButton.setOnClickListener {
            launch(UI) {
                val resultsText = run(context + CommonPool) {
                    individualDao.deleteAll()

                    val individual = Individual()
                    individual.firstName = "Jeff"
                    individual.lastName = "Campbell"
                    individualDao.insert(individual)

                    val lastInsertedId = individualDao.findLastInsertedId()
                    Log.d("Test", "Last Id [$lastInsertedId]")

                    return@run "ACTUAL RESULTS: ${individualDao.findLastModified(lastInsertedId)}\n" +
                            "EXPECTED RESULTS: ${individualDao.findById(lastInsertedId)?.lastModified}"
                }

                resultTextView.text = resultsText
            }
        }

        individualDao.findAllLive().observe(this, Observer { list ->
            Log.i("Sample", "==== Individual Table Changed ====")
            list?.forEach { individual ->
                Log.i("Sample", "Individual [${individual.getFullName()}]")
            }
        })

    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.home -> {
                finish()
                return true
            }
            else -> return super.onOptionsItemSelected(item)
        }
    }

//    companion object : ActivityCompanion<IntentOptions>(IntentOptions, SampleActivity::class)
}
