package com.castlabs.sdk.analytics_demo.activities

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.castlabs.android.player.AbstractPlayerListener
import com.castlabs.android.player.exceptions.CastlabsPlayerException
import com.castlabs.sdk.analytics_demo.AnalyticsDemo
import com.castlabs.sdk.analytics_demo.databinding.ActivityPlayerBinding
import com.castlabs.utils.Log
import com.google.android.material.snackbar.Snackbar

class PlayerActivity : AppCompatActivity() {

	companion object {
		const val TAG = "PlayerActivity"
	}

	private lateinit var binding: ActivityPlayerBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
		binding = ActivityPlayerBinding.inflate(layoutInflater)
        setContentView(binding.root)
		addPlayerListener()
		openPlayer()
    }

	override fun onStart() {
		super.onStart()
		binding.playerView.lifecycleDelegate.start(this)
	}

	override fun onResume() {
		super.onResume()
		binding.playerControllerView.bind(binding.playerView)
		binding.progressBar.bind(binding.playerView.playerController)
		binding.playerView.lifecycleDelegate.resume()
	}

	override fun onStop() {
		super.onStop()
		binding.playerControllerView.unbind()
		binding.progressBar.unbind()
		binding.playerView.lifecycleDelegate.releasePlayer(false)
	}

	private fun addPlayerListener() {
		val playerController = binding.playerView.playerController
		playerController.addPlayerListener(object: AbstractPlayerListener() {
			override fun onError(error: CastlabsPlayerException) {
				val errorMessage = "Player error: ${error.message}"
				Log.e(TAG, errorMessage, error)
				showError(errorMessage)
			}
		})
	}

	private fun openPlayer() {
		try {
			binding.playerView.playerController.open(intent.extras!!)
		}
		catch (e: Exception) {
			val errorMessage = "Error while opening the player: ${e.message}"
			Log.e(TAG, errorMessage, e)
			showError(errorMessage)
		}
	}

	private fun showError(error: String) {
		Snackbar.make(binding.playerView, error, Snackbar.LENGTH_INDEFINITE).show()
	}
}
