package hh.dejsem.net;

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

/**
 * copy to peer asynchronously
 */
public class PushToPeer extends LongAsyncTask {
	NetConnPeer dataConn;

	public PushToPeer(D d, NetTaskRef netTaskRef) throws Exception {
		super(d, netTaskRef);
		if (K.netNode == null) K.netNode = new NetNode(d);
		dataConn = new NetConnPeer(d, netTaskRef, false);
		// getPeerHost() must be called here from main process in order to use cmdConn serially
		// netConn.peerIp = (InetSocketAddress)SrvCmd.GETPEER.exec(d, null);   // atavismus, PEER se teď získá přes UDP
	}

	@Override
	protected Void doInBackground(Void... params) {
		super.doInBackground(params);
		try {
			// netConn.peerIp = netConn.getPeerHost_UDP();   // přesunuto do NetConnPeer.pushBatchSize  // atavismus
			if(netTaskRef.go) dataConn.pushBatchSize(netTaskRef.getProgress().es);
		}
		catch (Exception e) {
			if(!K.End.class.isInstance(e)) abend("peer PUSH", e);
			try { dataConn.connClose(); } catch(Exception x) {}
			return null;
		}

		String fn = "";
		try {
			for(String from: args.getStringArray(K.FILES_FROM_KEY))
				if(netTaskRef.go) {
					fn = from;
					dataConn.pushPeer(from);
				}
			if(netTaskRef.go) dataConn.endOfData();
		}
		catch (Exception e) {
			if(!K.End.class.isInstance(e)) {
				String peer = "";
				if(dataConn.peerIp != null) peer = dataConn.peerIp.getHostName();
				abend(String.format("COPY %s to peer %s", fn, peer), e);
			}
		}
		finally { try { dataConn.connClose(); } catch(Exception e) {} }
		return null;
	}

	@Override
	void completePostExecute() { d.l(3, "PUSHPEER batch finished"); }
}