package hh.dejsem;

import android.content.Context;
import android.content.Intent;
import android.os.Messenger;
import android.support.v7.app.AppCompatActivity;

import java.lang.ref.WeakReference;
import java.util.HashSet;
import java.util.Set;

import hh.lib.AbendDialogFragment;
import hh.lib.D;

public class GetReady implements PassW.PasswListener, SdUri.SDUriListener, AbendDialogFragment.IgnoreAbend {

	public interface ReadyListener { void onReady(boolean ok); }

	static GetReady instance = null;

	public static boolean isReady(D d) {
		final boolean ready = PassW.isReady() && SdUri.isReady();
		d.l(4, "isReady=" + ready);
		return ready;
	}

	D d;
	Context c;

	Set subscribers = new HashSet();
	private GetReady() {}

	public static void getReady(D d, Object subscriber) {
		if(instance == null) {
			instance = new GetReady();
			instance.d = d.klon(instance);
			instance.d.l(4, "getReady");
			if(isReady(instance.d)) ((ReadyListener)subscriber).onReady(true);
			else {
				instance.c = (Context)subscriber;
				instance.subscribers.add(subscriber);
				instance.go(subscriber);
			}
		}
		else {
			if(isReady(instance.d)) ((ReadyListener)subscriber).onReady(true);
			else instance.subscribers.add(subscriber);
		}
	}

	@Override
	public void onPasswReady(int result) {
		if(result < PassW.PW_BAD) {
			SdUri.subscriber = this;
			c.startActivity(new Intent(c, SdUri.class));
		}
		else result(false);
		instance = null;
	}

	@Override
	public void onSDPermissionReady() { result(true); }

	@Override
	public void ignoreAbend(boolean ignore) { if(!ignore) d.getAct().finish(); }

	void go(Object subscriber) {
		d.l(4, "go");
		K.app = c.getApplicationContext();
		D.applMsgr = new WeakReference<Messenger>(d.actMsgr);
		new PassW(d, (AppCompatActivity)subscriber, this);
	}

	void result(boolean success) {
		d.l(4, "notifying subscribers: success=" + success);
		for(Object subscriber: subscribers) ((ReadyListener)subscriber).onReady(success);
		subscribers.clear();
	}
}
