package org.needhamtrack.nytc.screens.event

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import kotlinx.android.synthetic.main.activity_event.*
import org.needhamtrack.nytc.R
import org.needhamtrack.nytc.base.BaseMvpActivity
import org.needhamtrack.nytc.base.PresenterConfiguration
import org.needhamtrack.nytc.models.AttemptResult
import org.needhamtrack.nytc.models.Event
import org.needhamtrack.nytc.screens.event.editmark.EditMarkDialogFragment
import org.needhamtrack.nytc.screens.event.officiate.OfficiateFragment
import org.needhamtrack.nytc.screens.event.overview.OverviewFragment

class EventActivity : BaseMvpActivity<EventContract.Presenter>(), EventContract.View, EditMarkDialogFragment.SaveMarkClickListener {
    private val overviewFragment by lazy { supportFragmentManager.findFragmentByTag(OverviewFragment.TAG) as? OverviewFragment ?: OverviewFragment.newInstance(event) }
    private val officiateFragment by lazy { supportFragmentManager.findFragmentByTag(OfficiateFragment.TAG) as? OfficiateFragment ?: OfficiateFragment.newInstance(event) }
    private val event by lazy { intent.getSerializableExtra(EVENT_EXTRA) as Event }

    override fun onViewCreated(savedInstanceState: Bundle?) {
        super.onViewCreated(savedInstanceState)
        setSupportActionBar(toolbar)
        goToOverview()
    }

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

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when (item?.itemId) {
            R.id.switch_view -> {
                return presenter.switchViewsClick()
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun goToOverview() {
        supportFragmentManager.beginTransaction().replace(R.id.content_frame, overviewFragment, OverviewFragment.TAG).commit()
    }

    override fun goToGuidedOfficiate() {
        supportFragmentManager.beginTransaction().replace(R.id.content_frame, officiateFragment, OfficiateFragment.TAG).commit()
    }

    override val layoutResourceId = R.layout.activity_event

    override fun createPresenter(configuration: PresenterConfiguration): EventContract.Presenter {
        return EventPresenter(this, configuration, event)
    }

    override fun onSaveClick(runnerId: Int, attemptNumber: Int, attemptResult: AttemptResult) {
        overviewFragment.onSaveClick(runnerId, attemptNumber, attemptResult)
    }


    companion object {
        const val EVENT_EXTRA = "_event-extra_"
        fun startIntent(context: Context, event: Event) = Intent(context, EventActivity::class.java)
                .apply { putExtra(EVENT_EXTRA, event) }
    }
}