package hh.dejsem;

import android.content.Intent;
import android.content.UriPermission;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.provider.DocumentFile;

import java.util.List;

import hh.lib.AbendDialogFragment;

/**
 * hledá UriPermission s cestou k SD Card a příslušné Uri ukládá
 * - je to Activity ...
 */
public class SdUri extends Act implements AbendDialogFragment.IgnoreAbend {

	public static final String SD_CARD_URI_PATH_KEY = "SD_CARD_URI_PATH_KEY";
	public static Uri SD_CARD_URI = null;

	public interface SDUriListener { void onSDPermissionReady(); }

	public static boolean isReady() { return SdUri.SD_CARD_URI != null; }

	public static void clearPermissions() {
		Prefs.sp.edit().remove(SD_CARD_URI_PATH_KEY).apply();
		SD_CARD_URI = null;
	}

	static SDUriListener subscriber;

	@Override
	public void onCreate(Bundle b) {
		super.onCreate(b);
	}

	@Override
	public void onStart() {
		super.onStart();
		getSdUri();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(d.ll(4)) d.l(String.format("onActivityResult: requestCode=%d, resultCode=%d", requestCode, resultCode));
		if(resultCode == RESULT_OK && requestCode == K.CHOOSE_SD_CARD_TREE) saveUriPermissions(data);
	}

	@Override
	public void ignoreAbend(boolean ignore) {
		if(ignore) {
			ready();
		}
		else ((AbendDialogFragment.IgnoreAbend)subscriber).ignoreAbend(false);

	}

	void ready() {
		subscriber.onSDPermissionReady();
		finish();
	}

	void getSdUri() {
		List<UriPermission> pups = persistedUriPermissions();
		String sdUriPath = Prefs.sp.getString(SD_CARD_URI_PATH_KEY, "");
		if(!pups.isEmpty() && !sdUriPath.equals(""))
			for(UriPermission up: pups) {
				Uri u = up.getUri();
				String p = u.getPath();
				if(p.equals(sdUriPath)) {
					SD_CARD_URI = u;
					K.SD_CARD_ROOT_DOC_FILE = DocumentFile.fromTreeUri(this, u);
				}
			}
		if(SD_CARD_URI == null) getSdTree();
		else {
			ready();}
	}

	void saveUriPermissions(Intent data) {
		Uri sdUri = data.getData();
		final int flags = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
		getContentResolver().takePersistableUriPermission(sdUri, flags);
		String uriPath = sdUri.getPath();
		d.l(4, String.format("SD card uri path=%s", uriPath));
		Prefs.sp.edit().putString(SD_CARD_URI_PATH_KEY, uriPath).apply();
		SD_CARD_URI = sdUri;
		K.SD_CARD_ROOT_DOC_FILE = DocumentFile.fromTreeUri(this, sdUri);
		persistedUriPermissions();
		ready();
	}

	/**
	 * vytahuje a vrací UriPermission a případně opisuje do logu
	 * @return
	 */
	List<UriPermission> persistedUriPermissions() {
		List<UriPermission> pups = getContentResolver().getPersistedUriPermissions();
		if(d.ll(4)) {
			if(pups.isEmpty()) d.l("persisted uri permissions empty");
			else {
				d.l("persisted uri permissions:");
				for(UriPermission up : pups) d.l(up.toString());
				d.l(String.format("SD card uri path=%s", Prefs.sp.getString(SD_CARD_URI_PATH_KEY, "")));
			}
		}
		return pups;
	}

	/**
	 * volba SD card tree
	 */
	void getSdTree() { startActivityForResult(new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE), K.CHOOSE_SD_CARD_TREE); }
}
