package com.castlabs.sdk.conviva_demo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.castlabs.android.player.PlayerConfig;
import com.castlabs.android.player.PlayerController;
import com.castlabs.android.player.PlayerView;
import com.castlabs.android.player.exceptions.CastlabsPlayerException;
import com.castlabs.android.player.playlist.MultiControllerPlaylist;
import com.castlabs.sdk.playerui.PlayerControllerProgressBar;
import com.castlabs.sdk.playerui.PlayerControllerView;
import com.castlabs.utils.Log;
import com.google.android.material.snackbar.Snackbar;

public class MultiControllerPlaylistDemo extends Activity {

	public static final String PLAY_BACKGROUND = "playBackground";
	public static final String BACK_PLAYERS = "backPlayers";
	public static final String FORWARD_PLAYERS = "forwardPlayers";

	private static final String TAG = "PlaylistDemo";
	private static final String SAVED_STATE = "savedState";

	private PlayerView playerView;
	private PlayerControllerView playerControllerView;
	private PlayerControllerProgressBar progressBar;
	private Button btPrev;
	private Button btNext;
	private MultiControllerPlaylist playlist;

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

		playerView = findViewById(R.id.playerView);
		playerControllerView = findViewById(R.id.playerControllerView);
		progressBar = findViewById(R.id.progressBar);

		initButtons();
		initPlaylist();
		startPlayback(savedInstanceState);
    }

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

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

	@Override
	protected void onStop() {
		super.onStop();
		playerView.getLifecycleDelegate().releasePlayer(false);
		playerControllerView.unbind();
		progressBar.unbind();
	}

	private void initButtons() {
		btPrev = findViewById(R.id.btPrev);
		btPrev.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				playlist.previousItem();
			}
		});

		btNext = findViewById(R.id.btNext);
		btNext.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				playlist.nextItem();
			}
		});
	}

	private void initPlaylist() {

		Intent intent = getIntent();
		boolean playBackground = intent.getBooleanExtra(PLAY_BACKGROUND, false);
		int backPlayers = intent.getIntExtra(BACK_PLAYERS, 1);
		int forwardPlayers = intent.getIntExtra(FORWARD_PLAYERS, 1);

		playlist = new MultiControllerPlaylist.Builder(playerView)
				.playBackground(playBackground)
				.backPlayers(backPlayers)
				.forwardPlayers(forwardPlayers)
				.nextItemThresholdMs(MultiControllerPlaylist.ITEM_THRESHOLD_UPON_START)
				.itemChangeFlags(MultiControllerPlaylist.KEEP_ALL)
				.listener(getPlaylistListener())
				.get();
	}

	private void startPlayback(Bundle savedInstanceState) {
		try {
			if (savedInstanceState == null) {
				Parcelable[] configs = getIntent().getExtras().getParcelableArray(MainActivity.INTENT_PLAYLIST);
				playlist.open(configs);
			}
			else {
				Bundle bundle = savedInstanceState.getBundle(SAVED_STATE);
				playlist.open(bundle);
			}
		}
		catch (Exception e) {
			showError(e.getMessage());
		}
	}

	private MultiControllerPlaylist.PlaylistListener getPlaylistListener() {
		return new MultiControllerPlaylist.PlaylistListener() {
			@Override
			public void onItemChange(@NonNull PlayerConfig newConfig, @Nullable PlayerController oldController, @Nullable PlayerController newController) {
				playerControllerView.unbind();
				progressBar.unbind();

				if (oldController != null) {
					oldController.movePlayerListeners(newController);
				}
				if (newController != null) {
					playerControllerView.bind(newController, playerView, playlist);
					progressBar.bind(newController);
				}

				btPrev.setEnabled(playlist.getCurrentItemIndex() != 0);
				btNext.setEnabled(playlist.getCurrentItemIndex() != playlist.getSize() - 1);
			}

			@Override
			public void onControllerCreate(@NonNull PlayerController playerController) {

			}

			@Override
			public PlayerConfig onControllerLoad(@NonNull PlayerConfig config, @NonNull PlayerController playerController) {
				return config;
			}

			@Override
			public void onControllerRelease(@NonNull PlayerController playerController) {

			}

			@Override
			public void onControllerDestroy(@NonNull PlayerController playerController) {

			}

			@Override
			public void onControllerError(@NonNull PlayerController controller, @NonNull CastlabsPlayerException error, @NonNull PlayerConfig config) {
				showError(error.getMessage());
				if (error.getSeverity() == CastlabsPlayerException.SEVERITY_ERROR) {
					playlist.removeItem(config);
				}
			}

			@Override
			public void onPlaylistEndReached(boolean willLoop) {

			}
		};
	}

	private void showError(String errorMessage) {
		Log.e(TAG, errorMessage);
		Snackbar.make(playerView, errorMessage, Snackbar.LENGTH_SHORT).show();
	}
}
