package com.demoscene.tv

import android.content.Intent
import android.os.Bundle
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import androidx.leanback.app.BrowseSupportFragment
import androidx.leanback.widget.*
import com.demoscene.tv.data.DemoDataProvider
import com.demoscene.tv.model.Demo
import com.demoscene.tv.ui.CardPresenter

/**
 * Main TV Activity with Netflix-style browse interface
 */
class MainActivity : FragmentActivity() {

    private lateinit var mRowsAdapter: ArrayObjectAdapter

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

        val fragment = supportFragmentManager.findFragmentById(R.id.main_browse_fragment)
                as BrowseSupportFragment

        setupUIElements(fragment)
        loadRows(fragment)
        setupEventListeners(fragment)
    }

    private fun setupUIElements(fragment: BrowseSupportFragment) {
        // Set colors
        fragment.brandColor = ContextCompat.getColor(this, R.color.primary)
        fragment.searchAffordanceColor = ContextCompat.getColor(this, R.color.primary_dark)

        // Set header
        fragment.headersState = BrowseSupportFragment.HEADERS_ENABLED
        fragment.isHeadersTransitionOnBackEnabled = true
        fragment.title = "Demoscene TV"
    }

    private fun loadRows(fragment: BrowseSupportFragment) {
        val categoryRows = DemoDataProvider.getCategoryRows()
        
        mRowsAdapter = ArrayObjectAdapter(ListRowPresenter())

        val cardPresenter = CardPresenter()

        for (categoryRow in categoryRows) {
            val listRowAdapter = ArrayObjectAdapter(cardPresenter).apply {
                categoryRow.demos.forEach { demo ->
                    add(demo)
                }
            }

            val header = HeaderItem(categoryRow.title)
            mRowsAdapter.add(ListRow(header, listRowAdapter))
        }

        fragment.adapter = mRowsAdapter
    }

    private fun setupEventListeners(fragment: BrowseSupportFragment) {
        fragment.onItemViewClickedListener = ItemViewClickedListener()
    }

    private inner class ItemViewClickedListener : OnItemViewClickedListener {
        override fun onItemClicked(
            itemViewHolder: Presenter.ViewHolder?,
            item: Any?,
            rowViewHolder: RowPresenter.ViewHolder?,
            row: Row?
        ) {
            if (item is Demo) {
                val intent = Intent(this@MainActivity, PlayerActivity::class.java)
                intent.putExtra("DEMO_TITLE", item.title)
                intent.putExtra("DEMO_YOUTUBE_URL", item.youtubeUrl)
                intent.putExtra("DEMO_GROUP", item.group)
                intent.putExtra("DEMO_YEAR", item.year)
                intent.putExtra("DEMO_PLATFORM", item.platform)
                startActivity(intent)
            }
        }
    }
}
