package com.castlabs.sdk.demos;

import android.app.Activity;
import android.os.Bundle;
import android.os.Parcelable;
import androidx.annotation.NonNull;

import com.google.android.material.snackbar.BaseTransientBottomBar;
import com.google.android.material.snackbar.Snackbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import com.castlabs.android.player.AbstractPlayerListener;
import com.castlabs.android.player.SingleControllerPlaylist;
import com.castlabs.android.player.PlayerConfig;
import com.castlabs.android.player.PlayerView;
import com.castlabs.android.player.exceptions.CastlabsPlayerException;
import com.castlabs.sdk.playerui.PlayerControllerView;

public class ConcatenatingPlaybackDemo extends Activity {
	private static final String TAG = "SimplePlaybackDemo";
	private static final String SAVED_PLAYBACK_STATE_BUNDLE_KEY = "SAVED_PLAYBACK_STATE_BUNDLE_KEY";
	// This is the player view that we use to start playback
	private PlayerView playerView;
	private PlayerControllerView playerControllerView;
	private SingleControllerPlaylist pc;

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

		// Get the view components from the layout
		playerView = (PlayerView) findViewById(R.id.player_view);
		// Get the controller view
		playerControllerView = (PlayerControllerView) findViewById(R.id.player_controls);

		// Set up Previous and Next button listeners
		findViewById(R.id.buttonPrevious).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				pc.previousItem();
			}
		});

		findViewById(R.id.buttonNext).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				pc.nextItem();
			}
		});
		// Here we create the SingleControllerPlaylist
		pc = new SingleControllerPlaylist(this, new PlaylistListenerImpl());

		// Optional: set Playlist wrap around
		pc.setWrapAroundPlaylistEdges(true);

		// Subscribe for the playback errors
		pc.addPlayerListener(new PlayerListenerImpl());
		// Set it as the PlayerController in our PlayerView
		playerView.setPlayerController(pc);

		try {
			if (savedInstanceState == null) {
				Parcelable[] configs;

				Log.d(TAG, "Opening playback from intent bundle");
				// This demo assumes that you send an intent to this Activity that contains the
				// playback information.
				if (getIntent() != null) {
					configs = getIntent().getExtras().getParcelableArray(MainActivity.INTENT_PLAYLIST);
					if (configs == null) {
						throw new IllegalArgumentException("Expected an ArrayList of PlayerConfig for INTENT_PLAYLIST key.");
					}
					// Start playback
					pc.open(configs);
				} else {
					Snackbar.make(playerView, "No intent specified", Snackbar.LENGTH_INDEFINITE).show();
				}
			} else {
				Log.d(TAG, "Opening playback from saved state");
				// Start playback
				Bundle playbackBundle = savedInstanceState.getBundle(SAVED_PLAYBACK_STATE_BUNDLE_KEY);
				if (playbackBundle == null) {
					throw new IllegalArgumentException("Expected saved Playback state");
				}
				pc.openState(playbackBundle);
			}
		} catch (IllegalArgumentException e) {
			Log.e(TAG, "Error while opening player: " + e.getMessage(), e);
			Snackbar.make(playerView, "Error while opening player: " + e.getMessage(),
					Snackbar.LENGTH_INDEFINITE).show();
		}
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		boolean handled = false;
		if (playerControllerView != null && playerControllerView.getVisibility() == View.VISIBLE) {
			handled = playerControllerView.dispatchKeyEvent(event);
		} else { // Not visible
			if (event.getAction() == KeyEvent.ACTION_DOWN) {
				handled = playerControllerView.dispatchKeyEvent(event);
			}
		}
		return handled || super.dispatchKeyEvent(event);
	}

	// Delegate the onStart event to the player views lifecycle delegate.
	// The delegate will make sure that the screen safer will be disabled and
	// the display will not go to sleep
	@Override
	protected void onStart() {
		super.onStart();
		playerView.getLifecycleDelegate().start(this);
	}

	// Delegate the onResume event to the player views lifecycle delegate.
	// The delegate ensures that the player recovers from a saved state. This needs to
	// be implemented to ensure the the user can for example go to the home screen and
	// come back to this activity.
	@Override
	protected void onResume() {
		super.onResume();

		// Set it as the PlayerController in our PlayerView
		playerView.setPlayerController(pc);

		// Bind the controller view
		playerControllerView.bind(playerView);

		playerView.getLifecycleDelegate().resume();
	}

	// Delegate the onStop event to the player views lifecycle delegate.
	// We release the player when the activity is stopped. This will release all the player
	// resources and save the current playback state. Saving the state is required so the
	// onResume callback can recover properly.
	@Override
	protected void onStop() {
		super.onStop();

		// Unbind the player controller view
		playerControllerView.unbind();
		playerView.getLifecycleDelegate().releasePlayer(false);
	}

	// Save the playback state when the activity is destroyed in order to correctly
	// resume after the activity is re-created again i.e. onCreate is called
	@Override
	public void onSaveInstanceState(Bundle outState) {
		// Save the playlist state in order to re-open the playlist upon activity being destroyed
		Bundle savedStateBundle = new Bundle();
		playerView.getPlayerController().saveState(savedStateBundle);
		outState.putBundle(SAVED_PLAYBACK_STATE_BUNDLE_KEY, savedStateBundle);

		super.onSaveInstanceState(outState);
	}

	private static final class PlaylistListenerImpl extends SingleControllerPlaylist.AbstractPlaylistListener {
		@Override
		public void onItemChange(@NonNull PlayerConfig config) {
			Log.d(TAG, "onItemChange: " + config.contentUrl);
		}
	}

	private final class PlayerListenerImpl extends AbstractPlayerListener {
		@Override
		public void onError(@NonNull CastlabsPlayerException error) {
			if (error.getSeverity() == CastlabsPlayerException.SEVERITY_ERROR) {
				Snackbar.make(playerView, "Error while opening player: " + error.getMessage(),
						BaseTransientBottomBar.LENGTH_INDEFINITE).show();
			} else {
				Log.e(TAG, "Error while opening player: " + error.getMessage());
			}
		}
	}
}
