package edu.fichte.pbi.ide.views;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;

import org.eclipse.jface.action.Action;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;
import org.osgi.framework.Bundle;

import edu.fichte.pbi.ide.Activator;

public class HelpView extends ViewPart {

	public static final String ID = "edu.fichte.pbi.ide.browser";
	private Browser browser;

	@Override
	public void createPartControl(Composite parent) {
		browser = new Browser(parent, SWT.NONE);
		browser.setJavascriptEnabled(true);
		Bundle bundle = Activator.getDefault().getBundle();
		File targetRoot = bundle.getDataFile("");
		File indexhtml = new File(targetRoot, "help/index.html");
		if(!indexhtml.canRead()){
			// must copy the html from the bundle .jar to the data file location
			copyPathFromBundleToFSRecursive(bundle, "help", targetRoot);
		}
		try {
			browser.setUrl(indexhtml.toURI().toURL().toExternalForm());
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		
		Action back = new Action("back") {
			@Override
			public void run() {
				browser.back();
			}
		};
		getViewSite().getActionBars().getToolBarManager().add(back);

//		URL mainUrl = Activator.getDefault().getBundle().getEntry("help/Main.html");
	}

	public static void copyPathFromBundleToFSRecursive(Bundle bundle, String path,
			File targetRoot) {
		Enumeration<String> entryPaths = bundle.getEntryPaths(path);
		while(entryPaths.hasMoreElements()){
			String entryPath = entryPaths.nextElement();
			if(entryPath.endsWith("/")) {
				copyPathFromBundleToFSRecursive(bundle, entryPath, targetRoot);
			} else {
				URL entry = bundle.getEntry(entryPath);
				File target = new File(targetRoot, entryPath);
				byte[] buf = new byte[10000];
				int c = 0;
				try {
					InputStream in = entry.openStream();
					target.getParentFile().mkdirs();
					target.createNewFile();
					BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(target));
					while(-1!=(c=in.read(buf))){
						out.write(buf, 0, c);
					}
					out.close();
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	@Override
	public void setFocus() {
		browser.setFocus();
	}
}
