package com.castlabs.sdk.mediasession_demo;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.Nullable;

import com.castlabs.android.player.PlayerConfig;
import com.castlabs.android.player.PlayerView;
import com.castlabs.sdk.mediasession.MediaSessionBuilder;
import com.castlabs.sdk.mediasession.MediaSessionPlugin;
import com.castlabs.sdk.playerui.PlayerControllerProgressBar;
import com.castlabs.sdk.playerui.PlayerControllerView;

public class SimplePlaybackDemo extends Activity {

	private static final String TAG = "SimplePlaybackDemo";

	private PlayerView playerView;
	private PlayerControllerView playerControllerView;
	private PlayerControllerProgressBar progressBar;

	private final PlayerConfig playerConfig = new PlayerConfig.Builder("http://demo.cf.castlabs.com/media/TOS/abr/Manifest_clean_sizes.mpd")
		.metaData(new BundleBuilder()
			.put(MediaSessionPlugin.METADATA_KEY_TITLE, "Sample Title")
			.put(MediaSessionPlugin.METADATA_KEY_ARTIST, "Sample Artist")
			.put(MediaSessionPlugin.METADATA_KEY_ARTWORK_URI, getResourceUri(R.drawable.castlabs))
			.get())
		.get();

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_simple_playback_demo);

		// Initialize the PlayerView
		playerView = findViewById(R.id.player_view);
		playerControllerView = findViewById(R.id.player_controls);
		progressBar = findViewById(R.id.progress_bar);

		// Enable the media session
		MediaSessionBuilder mediaSessionBuilder = createMediaSessionBuilder();
		MediaSessionPlugin.enableMediaSession(playerView.getPlayerController(), mediaSessionBuilder);

		// Open the player
		openPlayer();
	}

	@Override
	protected void onStart() {
		super.onStart();
		playerView.getLifecycleDelegate().start(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		playerControllerView.bind(playerView);
		progressBar.bind(playerView.getPlayerController());
		playerView.getLifecycleDelegate().resume();
	}

	@Override
	protected void onStop() {
		super.onStop();
		playerControllerView.unbind();
		progressBar.unbind();
	}

	@Override
	protected void onDestroy() {
		playerView.getLifecycleDelegate().releasePlayer(false);
		super.onDestroy();
	}

	private void openPlayer() {
		playerView.getPlayerController().open(playerConfig);
	}

	private MediaSessionBuilder createMediaSessionBuilder() {
		return new MediaSessionBuilder();
	}

	private Uri getResourceUri(int resourceId) {
		return Uri.parse("android.resource://com.castlabs.sdk.mediasession_demo/" + resourceId);
	}
}
