package com.castlabs.sdk.broadpeak_demo;

import android.app.Activity;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import com.castlabs.android.player.AbstractPlayerListener;
import com.castlabs.android.player.PlayerConfig;
import com.castlabs.android.player.PlayerController;
import com.castlabs.android.player.PlayerView;
import com.castlabs.android.player.SingleControllerPlaylist;
import com.castlabs.android.player.exceptions.CastlabsPlayerException;
import com.castlabs.sdk.broadpeak_demo.ads.AdUi;
import com.castlabs.sdk.playerui.PlayerControllerView;
import com.google.android.material.snackbar.BaseTransientBottomBar;
import com.google.android.material.snackbar.Snackbar;

import java.util.List;

import androidx.annotation.NonNull;

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;
	private AdUi adUi;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_simple_playback_demo);
		findViewById(R.id.playlistControls).setVisibility(View.VISIBLE);
		findViewById(R.id.buttonNext).setOnClickListener(v -> pc.nextItem());
		findViewById(R.id.buttonPrevious).setOnClickListener(v -> pc.previousItem());
		findViewById(R.id.buttonRemovePrev).setOnClickListener(v -> {
			final int currentItemIndex = pc.getCurrentItemIndex();
			if (currentItemIndex >= 1) {
				final List<PlayerConfig> playlist = pc.getPlaylist();
				pc.removeItem(playlist.get(currentItemIndex - 1));
				Toast.makeText(this, "Removed item " + (currentItemIndex - 1), Toast.LENGTH_SHORT).show();
				Log.d(TAG, "Removed item: " + (currentItemIndex - 1));
			}
		});
		findViewById(R.id.buttonCurrent).setOnClickListener(v -> {
			final PlayerConfig currentItem = pc.getCurrentItem();
			pc.removeItem(currentItem);
			Toast.makeText(this, "Removed current item", Toast.LENGTH_SHORT).show();
			Log.d(TAG, "Removed current item");
		});

		// Get the view components from the layout
		playerView = (PlayerView) findViewById(R.id.player_view);
		adUi = findViewById(R.id.ad_ui);

		// Get the controller view
		playerControllerView = (PlayerControllerView) findViewById(R.id.player_controls);

		// Here we create the SingleControllerPlaylist
		pc = new SingleControllerPlaylist(this, new PlaylistListenerImpl());
		pc.setPlaylistWindowAfter(1);
		pc.setPlaylistWindowBefore(1);
		pc.setMaximumLoadedItems(3);
		// 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 (Exception 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);
		if (adUi != null) {
			adUi.bind(playerView.getPlayerController());
		}
	}

	// 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();
		if (adUi != null) {
			adUi.unbind();
		}
		// 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
		final PlayerController playerController = playerView.tryPlayerController();
		if (playerController != null) {
			final Bundle savedStateBundle = new Bundle();
			playerController.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());
			}
		}
	}
}
