package com.castlabs.sdk.mediasession_demo;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.media3.common.Player;
import androidx.media3.common.Player.Commands;
import androidx.media3.session.CommandButton;
import androidx.media3.session.DefaultMediaNotificationProvider;
import androidx.media3.session.MediaNotification;
import androidx.media3.session.MediaSession;
import androidx.media3.session.MediaSessionService;
import androidx.media3.session.MediaStyleNotificationHelper;
import androidx.media3.session.SessionCommand;
import androidx.media3.session.SessionCommands;

import com.castlabs.android.player.PlayerConfig;
import com.castlabs.android.player.PlayerController;
import com.castlabs.android.player.PlayerView;
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;
import com.google.android.material.snackbar.Snackbar;
import com.google.common.collect.ImmutableList;

import java.util.ArrayList;

public class SimplePlayServiceDemo extends Activity {

	private static final String TAG = "SimplePlayServiceDemo";
	private static final String ACTION_FAVORITES = "com.castlabs.sdk.demos.action.favorites";

	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);
		CustomMediaSessionService.playerController = playerView.getPlayerController();

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

	@SuppressLint("UnsafeOptInUsageError")
	private MediaSessionBuilder createMediaSessionBuilder() {
		// Create custom session commands (optional)
		SessionCommand favoritesCommand = new SessionCommand(ACTION_FAVORITES, Bundle.EMPTY);
		SessionCommands sessionCommands = MediaSession.ConnectionResult.DEFAULT_SESSION_COMMANDS.buildUpon()
			.add(favoritesCommand)
			.build();

		// Create custom command buttons (optional)
		CommandButton favoritesButton = new CommandButton.Builder(CommandButton.ICON_HEART_UNFILLED)
			.setDisplayName("Save to favorites")
			.setSessionCommand(favoritesCommand)
			.build();
		ArrayList<CommandButton> commandButtons = new ArrayList<>();
		commandButtons.add(favoritesButton);

		// Create custom player commands (optional)
		Commands playerCommands = new Commands.Builder()
			.add(Player.COMMAND_PLAY_PAUSE)
			.add(Player.COMMAND_PREPARE)
			.add(Player.COMMAND_STOP)
			.add(Player.COMMAND_SEEK_TO_NEXT)
			.add(Player.COMMAND_SEEK_TO_PREVIOUS)
			.add(Player.COMMAND_SEEK_IN_CURRENT_MEDIA_ITEM)
			.add(Player.COMMAND_GET_CURRENT_MEDIA_ITEM)
			.add(Player.COMMAND_GET_TIMELINE)
			.add(Player.COMMAND_GET_METADATA)
			.build();

		// Create a listener for custom commands (optional)
		MediaSessionBuilder.Listener listener = new MediaSessionBuilder.Listener() {
			@Override
			public void onCustomCommand(@NonNull MediaSession session,
										@NonNull MediaSession.ControllerInfo controller,
										@NonNull SessionCommand customCommand,
										@NonNull Bundle args) {
				if (customCommand.customAction.equals(ACTION_FAVORITES)) {
					String message = "Favorites button clicked";
					Log.d(TAG, message);
					Snackbar.make(playerView, message, Snackbar.LENGTH_LONG).show();
				}
			}
		};

		// Create Intent to launch activity when notification is clicked (Optional)
		Intent intent = new Intent(getApplicationContext(), getClass());
		intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
		PendingIntent pendingIntent = PendingIntent.getActivity(
			getApplicationContext(),
			0,
			intent,
			PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

		// Create media session builder
		return new MediaSessionBuilder()
			.setSessionCommands(sessionCommands)
			.setPlayerCommands(playerCommands)
			.setCommandButtons(commandButtons)
			.setListener(listener)
			.setSessionActivity(pendingIntent)
			.setCustomMediaSessionServiceClass(CustomMediaSessionService.class);
	}

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

	// Custom MediaSessionService (optional)
	@SuppressLint("UnsafeOptInUsageError")
	public static class CustomMediaSessionService extends MediaSessionService {

		private static PlayerController playerController;

		@Override
		public void onCreate() {
			super.onCreate();
			setMediaNotificationProvider(createMediaNotificationProvider());
		}

		@Nullable
		@Override
		public MediaSession onGetSession(@NonNull MediaSession.ControllerInfo controllerInfo) {
			if (playerController != null) {
				return MediaSessionPlugin.getMediaSession(playerController);
			} else {
				return null;
			}
		}

		private MediaNotification.Provider createMediaNotificationProvider() {
			DefaultMediaNotificationProvider provider = new DefaultMediaNotificationProvider.Builder(getApplicationContext()).build();
			provider.setSmallIcon(R.drawable.notifications_icon);
			return provider;
		}
	}
}
