package com.castlabs.sdk.downloads;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Helper functions for the downloader demo app
 */
public class Util {
	/**
	 * Helper constant to check for write permissions
	 */
	static final int PERMISSION_REQUEST = 1;

	/**
	 * Checks is we have permission to write to external storage, and requests it otherwise
	 *
	 * @param activity The activity
	 */
	static void checkAndAskPermissions(Activity activity) {
		final boolean hasWriteStoragePermission = Build.VERSION.SDK_INT >= Build.VERSION_CODES.R
				|| ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
		final boolean hasNotificationPermission = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU
				|| ContextCompat.checkSelfPermission(activity, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED;
		if (!hasWriteStoragePermission || !hasNotificationPermission) {
			final List<String> permissions = new ArrayList<>();
			if (!hasWriteStoragePermission) {
				permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
			}
			if (!hasNotificationPermission) {
				permissions.add(Manifest.permission.POST_NOTIFICATIONS);
			}
			ActivityCompat.requestPermissions(activity, permissions.toArray(new String[permissions.size()]), PERMISSION_REQUEST);
		}
	}

	/**
	 * Resolve the download folder for a given download ID
	 *
	 * @param downloadId The download ID
	 * @return The resolved download folder
	 */
	@NonNull
	static String getDownloadFolder(@NonNull Context context, @NonNull String downloadId) {
		final File moviesDir = context.getExternalFilesDir(Environment.DIRECTORY_MOVIES);
		return new File(moviesDir, downloadId).getAbsolutePath();
	}

	/**
	 * Utility to help us creating bundles
	 */
	static class BundleBuilder {
		private final Bundle bundle;

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

		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, boolean value) {
			bundle.putBoolean(key, value);
			return this;
		}

		BundleBuilder put(String key, ArrayList<? extends Parcelable> value) {
			bundle.putParcelableArrayList(key, value);
			return this;
		}

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

		Bundle get() {
			return bundle;
		}
	}
}
