package hh.dejsem.fm;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.RelativeLayout;

import java.io.File;
import java.net.URI;
import java.net.URLConnection;

import hh.dejsem.K;
import hh.dejsem.net.ExposeFile;
import hh.dejsem.net.PushToServer;
import hh.dejsem.net.SrvCmd;
import hh.lib.D;

/**
 * panel with local directory list
 */
class PanelLocalDir extends PanelDirView {

	PanelLocalDir(D d, RelativeLayout layout, String dirViewLabel, String newWorkDirName) {
		super(d);
		dirView = new DirListView(this, layout, dirViewLabel, K.LOC_FS);
		fm = new FMLocal(d);
		fm.enterDir(newWorkDirName);
		setUpDirView();
	}

	@Override
	void handOverServerCopy(NetTaskRef netTaskRef) {
		try { new PushToServer(d, netTaskRef).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); }
		catch(Exception e) { d.abendMsg("copy to server", e); }
	}

	@Override
	void handleClickedFile(String fn) {
		String fp = fm.fullPath(fn);
		File file = new File(fp);
		URI fURI = file.toURI();
		Uri u = new Uri.Builder()
				.scheme(fURI.getScheme())
				.encodedAuthority(fURI.getRawAuthority())
				.encodedPath(fURI.getRawPath())
				.query(fURI.getRawQuery())
				.fragment(fURI.getRawFragment())
				.build();
		String mimeType = URLConnection.guessContentTypeFromName(fn);
		if(mimeType == null) mimeType = "application/octet-stream";
		d.l(4, "fn=" + fn + ", uri=" + u + ", type=" + mimeType);
		Bundle b = new Bundle();
		b.putParcelable(Intent.EXTRA_STREAM, u);
		Intent i = new Intent(Intent.ACTION_VIEW).putExtras(b).setDataAndType(u, mimeType);
		try { d.getContext().startActivity(i); }
		catch(ActivityNotFoundException e) { d.getContext().startActivity(Intent.createChooser(i, "open file")); }
	}

	@Override
	void expose(String selection) throws Exception {
		int port = (Integer) SrvCmd.LONGTASK.exec(d, null);
		FragFM.sweepOutNetCmd(d);
		if(port == 0) throw new Exception("all server ports busy", null);
		EntitySize es = fm.reckon(new String[] { selection });
		Bundle parms = new Bundle();
		parms.putInt(K.PORT_KEY, port);
		parms.putString(K.FILES_FROM_KEY, selection);
		K.prepTransferOverview(d);
		FragFM.sweepOutNetCmd(d);

		// tady BACHA, operace expose dostane ze serveru URL, který umístí na clipboard;
		// celé by se to mělo proto nějak serializovat,
		//  ale jen na samotný expose, s ostatními operacemi expose nekoliduje
		NetTaskRef netTaskRef = new NetTaskRef(d, parms, es);
		d.l(4, String.format("netTaskRef=%s", netTaskRef));
		new ExposeFile(d, netTaskRef).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}
}
