package hh.dejsem.net;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.os.RemoteException;

import hh.dejsem.K;
import hh.dejsem.fm.NetTaskRef;
import hh.dejsem.fm.TransferAlert;
import hh.lib.D;

/**
 * asynchronous task for long job
 */
public class LongAsyncTask extends AsyncTask<Void, Void, Void> {
	D d;
	NetTaskRef netTaskRef;
	Bundle args;

	LongAsyncTask(D d, NetTaskRef netTaskRef) throws Exception {
		this.d = d.klon(this);
		this.netTaskRef = netTaskRef;
		args = netTaskRef.getArgs();
	}

	@Override
	protected void onPreExecute() {
		if(d.ll(4)) d.l("onPreExecute");
		K.transfProgress.registerTask(netTaskRef);
	}

	@Override
	protected Void doInBackground(Void... params) {
		if(d.ll(4)) d.l("executing asynchronously...");
		return null;
	}

	@Override
	protected void onPostExecute(Void v) {
		if(d.ll(4)) d.l("onPostExecute");
		K.transfProgress.unRegisterTask(netTaskRef);
		completePostExecute();
	}

	@Override
	protected void onProgressUpdate(Void... v) { if(d.ll(4)) d.l("onProgressUpdate"); }

	void completePostExecute() {};

	void notifyRefresh() {
		try {
			if(netTaskRef.d.actMsgr != null) netTaskRef.d.actMsgr.send(Message.obtain(null, K.MSG_REFRESH_LOC));
			if(netTaskRef.failedTimeStamp)     // bug in setLastModified()
				warning("at least one timestamp failed to be set to its original value due to device dependent bug in system");
		}
		catch (RemoteException x) { abend("error when notifying for refresh", x); }
	}

	void notifyRefreshFileList(int what) {
		try { if(netTaskRef.d.actMsgr != null) netTaskRef.d.actMsgr.send(Message.obtain(null, what)); }
		catch (RemoteException x) { abend("error when notifying for refresh", x); }
	}

	void warning(String txt) {
		K.app.startActivity(new Intent(K.app, TransferAlert.class)
				.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
				.putExtra(K.ACTION_KEY, K.TRANSFER_WARNING)
				.putExtra(K.TXT_KEY, txt)
		);
	}

	/**
	 * Ošetření ABENDu v prostředí nitě běžící na pozadí - spouští se aktivita s pop-up window.
	 *
	 * @param symptom the symptom
	 * @param e       the e
	 */
	void abend(String symptom, Exception e) {
		d.lvab(symptom, e);
		K.transfProgress.unRegisterTask(netTaskRef);
		K.app.startActivity(new Intent(K.app, TransferAlert.class)
				.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)     /*Intent.FLAG_ACTIVITY_SINGLE_TOP)*/
				.putExtra(K.ACTION_KEY, K.TRANSFER_ABEND)
				.putExtra(K.TXT_KEY, d.composeAbendMsg(symptom, e))
		);
	}
}
