package com.castlabs.sdk.downloads;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
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;

/**
 * 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) {
		if (!havePermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, activity)) {
			ActivityCompat.requestPermissions(activity, new String[]{
					Manifest.permission.WRITE_EXTERNAL_STORAGE
			}, PERMISSION_REQUEST);
		}
	}

	/**
	 * Checks if we have the requested permission
	 *
	 * @param permission The permission
	 * @param context    The context
	 * @return True if we have the permission
	 */
	static boolean havePermission(String permission, Context context) {
		return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
	}

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