package com.castlabs.sdk.mediasession_demo;

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

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

import com.castlabs.android.drm.DrmConfiguration;
import com.castlabs.android.drm.KeyStore;
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.exceptions.CastlabsPlayerException;
import com.castlabs.logutils.Log;
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;
	@Nullable
	private PlayerListener playerListener = null;
	@NonNull
	private final MediaSessionBuilder mediaSessionBuilder = createMediaSessionBuilder();

	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);

		playerListener = new PlayerListener();
		playerView.getPlayerController().addPlayerListener(playerListener);

		// 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.getPlayerController().removePlayerListener(playerListener);
		playerView.getLifecycleDelegate().releasePlayer(false);
		playerListener = null;
		super.onDestroy();
	}

	private void maybeDeleteLicense() {
		final DrmConfiguration drmConfiguration = playerConfig.drmConfiguration;
		if (drmConfiguration == null) {
			return;
		}
		KeyStore keyStore = PlayerController.getKeyStore();
		if (keyStore == null) {
			return;
		}
		if (drmConfiguration.offlineId == null || !keyStore.delete(drmConfiguration.offlineId)) {
			return;
		}
		Log.e(TAG, "DRM license key expired or not usable. Cleared key and reload");
	}

	private void openPlayer() {
		// Enable the media session
		MediaSessionPlugin.enableMediaSession(playerView.getPlayerController(), mediaSessionBuilder);
		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);
	}

	private class PlayerListener extends AbstractPlayerListener {
		@Override
		public void onError(@NonNull CastlabsPlayerException error) {
			Log.e(TAG, "Player error: " + error.getMessage(), error);
			// If license is expired, reopen
			if (error.getType() == CastlabsPlayerException.TYPE_KEY_EXPIRED) {
				Log.d(TAG, "License expired, restarting playback");
				maybeDeleteLicense();
				openPlayer();
			}
		}
	}
}
