package hh.dejsem.clipboard;

import android.content.ClipData;
import android.content.ClipDescription;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Handler;
import android.widget.Toast;

import hh.dejsem.K;
import hh.dejsem.net.NetData;
import hh.dejsem.net.SrvCmd;
import hh.lib.D;

public class Clipboard {

	D d;
	Context c;
	Handler.Callback h;
	ClipboardManager clipMgr;
	boolean test = false;

	public Clipboard(Context c, Handler.Callback h, D d) {
		this.d = d.klon(this);
		this.c = c;
		this.h = h;
		clipMgr = (ClipboardManager)c.getSystemService(Context.CLIPBOARD_SERVICE);
	}

	public String getCB() {
		if(clipMgr.hasPrimaryClip()) {
			final ClipData cd = clipMgr.getPrimaryClip();
			final int itemCnt = cd.getItemCount();
			return (itemCnt > 0 && cd.getItemAt(0).getText() != null ? cd.getItemAt(0).getText().toString() : "");
		}
		return "";
	}

	void setCB(String s) { clipMgr.setPrimaryClip(new ClipData(new ClipDescription("dejsem", new String[] {"text/plain"}), new ClipData.Item(s))); }

	void test() {
		if(test) setCB(K.testText);
		else setCB("");
		test = !test;
	}

	void clear() { setCB(""); }

	public boolean push() {
		d.getVb().vibrate(30);
		try {
			final String s = getCB();
			SrvCmd.PUSHCLIP.exec(d, new NetData(d, s));
//			K.histlist = null;   // histlist has changed, discard its local copy
			Toast.makeText(c, String.format("%d characters copied to shared clipboard", s.length()), Toast.LENGTH_LONG).show();
			return true;
		}
		catch(Exception e) {
			d.abendMsg("PUSH from clipboard", e);
			return false; }
	}

	public boolean pull() { return pull(""); }

	public boolean pull(String fn) {
		d.getVb().vibrate(30);
		try {
			String cb = (String)SrvCmd.PULLCLIP.exec(d, fn);
			K.cmdConnClose(d);
			setCB(cb);
			if(d.ll(4)) d.l(String.format("'%s' pulled from server", cb.length() > 64 ? cb.substring(0, 64) + "..." : cb));
			Toast.makeText(c, "" + cb.length() + " characters pulled from shared clipboard", Toast.LENGTH_LONG).show();
			return true;
		}
		catch(Exception e) {
			d.abendMsg("PULL to clipboard", e);
			return false;
		}
	}
}
