package hh.dejsem.net;

import android.os.Handler;
import android.os.Message;

import java.io.IOException;
import java.net.SocketException;

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

/**
 * copy from peer asynchronously in background
 */
public class PullFromPeer extends LongAsyncTask implements Handler.Callback {

	NetConnPeer netConn;
	Handler abendHandler = new Handler(this);   // handles requests for ABEND from thread

	/**
	 * Instantiates a new Pull from peer.
	 *
	 * @param d          the d
	 * @param netTaskRef the net task ref
	 * @throws Exception the exception
	 */
	public PullFromPeer(D d, NetTaskRef netTaskRef) throws Exception {
		super(d, netTaskRef);
		if(K.netNode == null) K.netNode = new NetNode(d);
		netConn = new NetConnPeer(this.d, netTaskRef, true);
		//SrvCmd.SETPEER.exec(d, netConn);	// bindSockToPeer() must be called here from main process because of serial cmdConn use // atavismus
	}

	@Override
	protected Void doInBackground(Void... params) {
		super.doInBackground(params);
		String to = "";
		try {
			to = args.getString(K.FILE_TO_KEY);
			try { netConn.acceptConnFromPeer(abendHandler); }
			catch (SocketException e) { throw new IOException("accepting conn from peer", e); }
			if(netTaskRef.go) netTaskRef.getProgress().es.setTargetSize(netConn.pullBatchSize());
			if(netTaskRef.go) netConn.pullDataFromPeer(to); }
		catch(Exception e) { if(!K.End.class.isInstance(e)) abend(String.format("copy from peer to dir %s", to), e); }
		finally { try { netConn.connClose(); } catch(Exception e) {} }
		return null;
	}

	@Override
	void completePostExecute() { notifyRefresh(); }

	@Override
	public boolean handleMessage(Message msg) { // msg contains message from exception
		abend("copy from peer", new Exception((String)(msg.obj)));
		try { netConn.connClose(); } catch(Exception e) {}
		return true;
	}
}