package com.castlabs.sdk.youbora_demo;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.castlabs.analytics.AnalyticsMetaData;
import com.castlabs.android.SdkConsts;
import com.castlabs.android.drm.Drm;
import com.castlabs.android.drm.DrmTodayConfiguration;
import com.castlabs.android.player.PlayerConfig;
import com.castlabs.android.player.VideoFilterConfiguration;
import com.castlabs.sdk.ima.ImaAdRequest;
import com.castlabs.sdk.youbora.YouboraPlugin;
import com.npaw.NpawPlugin;
import com.npaw.core.options.AnalyticsOptions;

import java.util.Arrays;
import java.util.List;

public class MainActivity extends AppCompatActivity {
	public static final String INTENT_PLAYLIST = "INTENT_PLAYLIST";
	private Demo[] DEMOS = new Demo[]{
			new Demo("Simple Clear Playback", "Plays an unencrypted stream",
					ReleasablePlayerPlaybackDemo.class,
					new BundleBuilder(false, "TOS")
							.put(SdkConsts.INTENT_URL, "https://demo.cf.castlabs.com/media/TOS/abr/Manifest_clean_sizes.mpd")
							.get()),

			new Demo("Simple Clear Playback - No Autoplay", "Plays an unencrypted stream without autoplay",
					ReleasablePlayerPlaybackDemo.class,
					new BundleBuilder(false, "TOS")
							.put(SdkConsts.INTENT_URL, "https://demo.cf.castlabs.com/media/TOS/abr/Manifest_clean_sizes.mpd")
							.put(SdkConsts.INTENT_START_PLAYING, false)
							.get()),

			new Demo("DASH Live Clear Playback", "Plays an unencrypted live DASH stream",
					ReleasablePlayerPlaybackDemo.class,
					new BundleBuilder(true, "LiveDASH")
							.put(SdkConsts.INTENT_URL, "https://livesim.dashif.org/livesim/testpic_2s/Manifest.mpd")
							.get()),

			new Demo("Simple Clear Playback - IMA Ads", "Plays an unencrypted stream with IMA ads",
					ReleasablePlayerPlaybackDemo.class,
					new BundleBuilder(false, "TOS")
							.put(SdkConsts.INTENT_URL, "https://demo.cf.castlabs.com/media/TOS/abr/Manifest_clean_sizes.mpd")
							.put(SdkConsts.INTENT_VIDEO_FILTER, new VideoFilterConfiguration.Builder()
									.maxWidth(1920)
							.get())
							// 3 prerolls skippable after 5 sec, 2 midrolls at 15sec skippable after 10 sec, 2 postrolls
							.put(SdkConsts.INTENT_ADVERTS_DATA, new ImaAdRequest("https://players.castlabs.com/ads/vmap?ad=0,1,2,start-5&ad=1,2,00:00:15-5&ad=1,2,end").toAdRequest())
							//.put(SdkConsts.INTENT_ADVERTS_DATA, new ImaAdRequest("https://pubads.g.doubleclick.net/gampad/ads?sz=640x480&iu=/124319096/external/ad_rule_samples&ciu_szs=300x250&ad_rule=1&impl=s&gdfp_req=1&env=vp&output=vmap&unviewed_position_start=1&cust_params=deployment%3Ddevsite%26sample_ar%3Dpremidpost&cmsid=496&vid=short_onecue&correlator=").toAdRequest())
							.get()),

		new Demo("Single Controller Playlist demo", "Creates a playlist with 3 protected items; TOS, BBB, TOS. This demo uses the SingleControllerPlaylist.",
			ConcatenatingPlaybackDemo.class,
			new BundleBuilder()
				.put(INTENT_PLAYLIST,
					new PlayerConfig[]{
						new PlayerConfig.Builder("https://demo.cf.castlabs.com/media/TOS/DASH/DEMO.mpd")
							.drmConfiguration(new DrmTodayConfiguration.Builder(
								DrmTodayConfiguration.DRMTODAY_STAGING,
								"purchase",
								"sessionId",
								"six",
								"dasheverywhere_demo",
								Drm.Widevine
							).get())
							.analyticsMetaData(YouboraPlugin.createMetadata(false, "TOS", new AnalyticsOptions.Builder()
								.contentTitle("TOS")
								.build()))
							.get(),
						new PlayerConfig.Builder("https://demo.cf.castlabs.com/media/bbb_abr/Manifest.mpd")
							.drmConfiguration(new DrmTodayConfiguration.Builder(
								DrmTodayConfiguration.DRMTODAY_PRODUCTION,
								"purchase",
								"default",
								"client_qa",
								"BBB_TEST",
								Drm.BestAvailable
							).get())
							.analyticsMetaData(YouboraPlugin.createMetadata(false, "BBB", new AnalyticsOptions.Builder()
								.contentTitle("BBB")
								.build()))
							.get(),
						new PlayerConfig.Builder("https://demo.cf.castlabs.com/media/shows/tos/Manifest.mpd")
							.drmConfiguration(new DrmTodayConfiguration.Builder(
								DrmTodayConfiguration.DRMTODAY_STAGING,
								"purchase",
								"p0",
								"six",
								"tos_next_gen_demo",
								Drm.Widevine
							).get())
							.analyticsMetaData(YouboraPlugin.createMetadata(false, "TOS", new AnalyticsOptions.Builder()
								.contentTitle("TOS")
								.build()))
							.get(),
					}
				)
				.get()),

			new Demo("Simple Clear Playback, offset", "Starts with 30 sec offset",
					ReleasablePlayerPlaybackDemo.class,
					new BundleBuilder(false, "TOS")
							.put(SdkConsts.INTENT_URL, "https://demo.cf.castlabs.com/media/TOS/abr/Manifest_clean_sizes.mpd")
							.put(SdkConsts.INTENT_POSITION_TO_PLAY, 30000000L)
							.get()),

			new Demo("Simple Clear Playback, session on play", "Starts in paused state, creates analytics upon user play",
					ReleasablePlayerPlaybackDemo.class,
					new BundleBuilder(false, "TOS")
							.put(SdkConsts.INTENT_URL, "https://demo.cf.castlabs.com/media/TOS/abr/Manifest_clean_sizes.mpd")
							.put(SdkConsts.INTENT_START_PLAYING, false)
							.put(SdkConsts.INTENT_ANALYTICS_SESSION_TYPE, SdkConsts.ANALYTICS_SESSION_TYPE_PLAY)
							.get()),
	};


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

		// (Optional) Youbora Sessions tracking
		//NpawPlugin youboraPlugin = ((DemoApp) getApplicationContext()).youboraPlugin;
		//youboraPlugin.getAppAnalytics().begin("MainActivity");

		ListView demosList = (ListView) findViewById(R.id.demos_list);
		List<Demo> demos = Arrays.asList(DEMOS);
		final ArrayAdapter<Demo> demoAdapter = new ArrayAdapter<Demo>(this, R.layout.demo_list_item, demos) {
			@Override
			@NonNull
			public View getView(int position, View convertView, @NonNull ViewGroup parent) {
				View view = convertView == null ? getLayoutInflater().inflate(R.layout.demo_list_item, parent, false) : convertView;
				Demo item = getItem(position);
				if (item != null) {
					((TextView) view.findViewById(R.id.title)).setText(item.name);
					((TextView) view.findViewById(R.id.description)).setText(item.description);
				}
				return view;
			}
		};

		demosList.setAdapter(demoAdapter);
		demosList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
				Demo item = demoAdapter.getItem(position);
				if (item != null) {
					item.start(MainActivity.this);
				}
			}
		});
	}

	static class Demo {
		public final String name;
		private final String description;
		private final Class<? extends Activity> activityClass;
		private final Bundle bundle;

		Demo(String name, String description, Class<? extends Activity> activityClass, Bundle bundle) {
			this.name = name;
			this.description = description;
			this.activityClass = activityClass;
			this.bundle = bundle;
		}

		void start(Context context) {
			context.startActivity(new Intent(context, activityClass).putExtras(bundle));
		}
	}

	private class BundleBuilder {
		private final Bundle bundle;

		BundleBuilder() {
			this.bundle = new Bundle();
		}

		BundleBuilder(boolean live, @NonNull String assetId) {
			this();

			// Youbora Options object, create and populate
			AnalyticsOptions options = new AnalyticsOptions();
			// We use the asset id as Youbora title, as an example
			options.setContentTitle(assetId);

			// Create AnalyticsMetadata using Youbora Options object
			AnalyticsMetaData analyticsMetaData = YouboraPlugin.createMetadata(live, assetId, options);
			analyticsMetaData.viewerId = "viewer_id";
			put(SdkConsts.INTENT_ANALYTICS_DATA, analyticsMetaData);
		}

		BundleBuilder put(String key, String value) {
			bundle.putString(key, value);
			return this;
		}

		BundleBuilder put(String key, int value) {
			bundle.putInt(key, value);
			return this;
		}

		BundleBuilder put(String key, long value) {
			bundle.putLong(key, value);
			return this;
		}

		BundleBuilder put(String key, boolean value) {
			bundle.putBoolean(key, value);
			return this;
		}

		BundleBuilder put(String key, Parcelable value) {
			bundle.putParcelable(key, value);
			return this;
		}

		Bundle get() {
			return bundle;
		}

		BundleBuilder put(String key, Parcelable[] value) {
			bundle.putParcelableArray(key, value);
			return this;
		}
	}
}
