/*
 * Created on 26.09.2005
 */
package org.ganttproject.impex.htmlpdf;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.URIResolver;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamSource;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.IJobManager;
import org.eclipse.core.runtime.jobs.Job;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;

import net.sourceforge.ganttproject.CustomProperty;
import net.sourceforge.ganttproject.IGanttProject;
import net.sourceforge.ganttproject.chart.Chart;
import net.sourceforge.ganttproject.export.ExportException;
import net.sourceforge.ganttproject.export.ExportFinalizationJob;
import net.sourceforge.ganttproject.export.Exporter;
import net.sourceforge.ganttproject.export.Stylesheet;
import net.sourceforge.ganttproject.export.TaskVisitor;
import net.sourceforge.ganttproject.export.Stylesheet.StylesheetType;
import net.sourceforge.ganttproject.gui.TableHeaderUIFacade;
import net.sourceforge.ganttproject.gui.UIFacade;
import net.sourceforge.ganttproject.gui.TableHeaderUIFacade.Column;
import net.sourceforge.ganttproject.gui.options.model.DefaultEnumerationOption;
import net.sourceforge.ganttproject.gui.options.model.EnumerationOption;
import net.sourceforge.ganttproject.gui.options.model.GPOption;
import net.sourceforge.ganttproject.gui.options.model.GPOptionGroup;
import net.sourceforge.ganttproject.language.GanttLanguage;
import net.sourceforge.ganttproject.resource.HumanResource;
import net.sourceforge.ganttproject.resource.ProjectResource;
import net.sourceforge.ganttproject.resource.ResourceManager;
import net.sourceforge.ganttproject.task.CustomColumn;
import net.sourceforge.ganttproject.task.CustomColumnsStorage;
import net.sourceforge.ganttproject.task.CustomColumnsValues;
import net.sourceforge.ganttproject.task.ResourceAssignment;
import net.sourceforge.ganttproject.task.Task;
import net.sourceforge.ganttproject.task.TaskManager;

abstract class ExporterBase implements Exporter {
    private IGanttProject myProject;
    private Chart myGanttChart;
    private GPOptionGroup myOptions;
    private Chart myResourceChart;
    private final SAXTransformerFactory myFactory;
    private UIFacade myUIFacade;
    private List mySelectedTasks;

    protected ExporterBase() {
        myFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    }
    protected EnumerationOption createStylesheetOption(String optionID, final Stylesheet[] stylesheets) {
        String[] names = new String[stylesheets.length];
        for (int i = 0; i < stylesheets.length; i++) {
            names[i] = stylesheets[i].getLocalizedName();
        }
        EnumerationOption stylesheetOption = new DefaultEnumerationOption(optionID, names) {
            public void commit() {
                super.commit();
                String value = getValue();
                for (int i=0; i<stylesheets.length; i++) {
                    if (stylesheets[i].getLocalizedName().equals(value)) {
                        setStylesheet(stylesheets[i]);
                    }
                }
            }

        };
        return stylesheetOption;
    }
    protected abstract String getStylesheetOptionID();
    static Object EXPORT_JOB_FAMILY = new String("Export job family");

    public void run(final File outputFile, List selectedTasks, final ExportFinalizationJob finalizationJob)
    throws Exception {
        mySelectedTasks = selectedTasks;
        final IJobManager jobManager = Platform.getJobManager();
        final List resultFiles = new ArrayList();
        final Job[] jobs = createJobs(outputFile, resultFiles);
        final IProgressMonitor monitor = jobManager.createProgressGroup();
        final IProgressMonitor familyMonitor = new IProgressMonitor() {
            public void beginTask(String name, int totalWork) {
                monitor.beginTask(name, totalWork);
            }
            public void done() {
                monitor.done();
            }
            public void internalWorked(double work) {
                monitor.internalWorked(work);
            }
            public boolean isCanceled() {
                return monitor.isCanceled();
            }
            public void setCanceled(boolean value) {
                monitor.setCanceled(value);
                if (value) {
                    System.err.println("ExporterBase: canceling value="+EXPORT_JOB_FAMILY);
                    jobManager.cancel(EXPORT_JOB_FAMILY);
                }
            }
            public void setTaskName(String name) {
                monitor.setTaskName(name);
            }
            public void subTask(String name) {
                monitor.subTask(name);
            }
            public void worked(int work) {
                monitor.worked(work);
            }
        };
        Job starting = new Job("starting") {
            protected IStatus run(IProgressMonitor monitor) {
                monitor.beginTask("Running export", jobs.length);
                for (int i=0; i<jobs.length; i++) {
                    if (monitor.isCanceled()) {
                        return Status.CANCEL_STATUS;
                    }
                    jobs[i].setProgressGroup(monitor, 1);
                    jobs[i].schedule();
                    try {
                        jobs[i].join();
                    } catch (InterruptedException e) {
                        myUIFacade.showErrorDialog(e);
                    }
                }
                Job finishing = new Job("finishing") {
                    protected IStatus run(IProgressMonitor monitor) {
                        monitor.done();
                        finalizationJob.run((File[]) resultFiles.toArray(new File[0]));
                        return Status.OK_STATUS;
                    }
                };
                finishing.setProgressGroup(monitor, 0);
                finishing.schedule();
                try {
                    finishing.join();
                } catch (InterruptedException e) {
                    myUIFacade.showErrorDialog(e);
                }
                return Status.OK_STATUS;
            }
        };
        starting.setProgressGroup(familyMonitor, 0);
        starting.schedule();
    }

    protected abstract Job[] createJobs(File outputFile, List resultFiles);

    public void setContext(IGanttProject project, UIFacade uiFacade, StylesheetType stylesheetType) {
        myGanttChart= uiFacade.getGanttChart();
        myResourceChart = uiFacade.getResourceChart();
        myProject = project;
        myUIFacade = uiFacade;
        /* Get appropriate set of stylesheets */
        final Stylesheet[] stylesheets = filterStylesheets(stylesheetType);
        EnumerationOption stylesheetOption= createStylesheetOption(getStylesheetOptionID(), stylesheets);
        stylesheetOption.lock();
        stylesheetOption.setValue(stylesheets[0].getLocalizedName());
        stylesheetOption.commit();
        myOptions = new GPOptionGroup("exporter.html", new GPOption[] {stylesheetOption});
        myOptions.setTitled(false);
    }

    /**
     * Return appropriate array of stylesheets according to their type; if type
     * is not set or is set to StylesheetType.all return all stylesheets
     * associated with exporter;
     * @param type of stylesheets to be selected
     * @return array of stylesheets of appropriate type
     */
    private Stylesheet[] filterStylesheets(StylesheetType stylesheetType) {
        Stylesheet[] stylesheets;
        Stylesheet[] allStylesheets = getStylesheets();
        if (stylesheetType==null || stylesheetType.equals(StylesheetType.all)) {
            stylesheets = allStylesheets;
        } else {
            List selectedStylesheets = new ArrayList<Stylesheet>();
            for (Stylesheet stylesheet: allStylesheets) {
                if (stylesheet.getStylesheetType().equals(stylesheetType)) {
                    selectedStylesheets.add(stylesheet);
                }
            }
            stylesheets = (Stylesheet[]) selectedStylesheets.toArray(new StylesheetImpl[0]);
        }
        return stylesheets;
    }

    protected UIFacade getUIFacade() {
        return myUIFacade;
    }
    protected IGanttProject getProject() {
        return myProject;
    }
    protected CustomColumnsStorage getCustomColumnStorage() {
        return getProject().getCustomColumnsStorage();
    }
    protected Chart getGanttChart() {
        return myGanttChart;
    }
    public GPOptionGroup getOptions() {
        return myOptions;
    }
    protected Chart getResourceChart() {
        return myResourceChart;
    }
    protected List getSelectedTasks() {
        return mySelectedTasks;
    }
    protected void startElement(String name, AttributesImpl attrs,
            TransformerHandler handler) throws SAXException {
        handler.startElement("", name, name, attrs);
        attrs.clear();
    }

    protected void startPrefixedElement(String name, AttributesImpl attrs,
            TransformerHandler handler) throws SAXException {
        handler.startElement("http://ganttproject.sf.net/", name, "ganttproject:"+name, attrs);
        attrs.clear();
    }
    protected void endElement(String name, TransformerHandler handler)
    throws SAXException {
        handler.endElement("", name, name);
    }
    protected void endPrefixedElement(String name, TransformerHandler handler)
    throws SAXException {
        handler.endElement("http://ganttproject.sf.net/", name, "ganttproject:"+name);
    }

    protected void addAttribute(String name, String value, AttributesImpl attrs) {
        if (value != null) {
            attrs.addAttribute("", name, name, "CDATA", value);
        } else {
            System.err.println("[GanttOptions] attribute '" + name
                    + "' is null");
        }
    }

    protected void emptyElement(String name, AttributesImpl attrs,
            TransformerHandler handler) throws SAXException {
        startElement(name, attrs, handler);
        endElement(name, handler);
        attrs.clear();
    }

    protected void textElement(String name, AttributesImpl attrs, String text, TransformerHandler handler) throws SAXException {
        if (text!=null) { 
            startElement(name, attrs, handler);
            handler.startCDATA();
            handler.characters(text.toCharArray(), 0, text.length());
            handler.endCDATA();
            endElement(name, handler);
            attrs.clear();
        }
    }

    protected SAXTransformerFactory getTransformerFactory() {
        return myFactory;
    }

    protected TransformerHandler createHandler(final URL xslUrl) throws MalformedURLException, UnsupportedEncodingException {
        try {
            getTransformerFactory().setURIResolver(new URIResolver() {
                final File myDirectory = new File(xslUrl.getFile()).getParentFile();
                public Source resolve(String href, String base) throws TransformerException {
                    return new StreamSource(new File(myDirectory, href));
                }
            });
//          URL encoded = new URL("file", "", URLEncoder.encode(xslUrl.toExternalForm(), "utf-8").substring(7));
//          String s1 = encoded.toString().replace("+", "%20");
            //String s1 = URLUTF8Encoder.encode(xslUrl.toString());
            //System.err.println("encoded:"+s1);
            URI xslUri;
            Document xslDocument;
            try {
                xslUri = new URI(xslUrl.toString().replace(" ", "%20"));
                xslDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xslUri.toASCIIString());
            } catch (URISyntaxException e) {
                e.printStackTrace();
                throw new MalformedURLException(e.getMessage());
            } catch (SAXException e) {
                e.printStackTrace();
                throw new MalformedURLException(e.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
                throw new MalformedURLException(e.getMessage());
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
                throw new MalformedURLException(e.getMessage());
            }
            Templates t = getTransformerFactory().newTemplates(new StreamSource(xslUri.toASCIIString()));
            TransformerHandler result = getTransformerFactory().newTransformerHandler(t);
            Transformer transformer = result.getTransformer();
            transformer.setOutputProperty(OutputKeys.METHOD, "xml");
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "fo:block");

            transformer.setOutputProperty(
                    "{http://xml.apache.org/xslt}indent-amount", "4");
            return result;

        } catch (TransformerConfigurationException e) {
            myUIFacade.showErrorDialog(e);
            throw new RuntimeException(e);
        }/* catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
		}
		 catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
		}*/
    }

    protected void addAttribute(String name, int value, AttributesImpl attrs) {
        addAttribute(name, String.valueOf(value), attrs);
    }


    protected String i18n(String key) {
        String text = GanttLanguage.getInstance().getText(key);
        return GanttLanguage.getInstance().correctLabel(text);
    }

    protected void writeColumns(TableHeaderUIFacade visibleFields, TransformerHandler handler) throws SAXException {
        AttributesImpl attrs = new AttributesImpl();
        int totalWidth = 0;
        for (int i=0; i<visibleFields.getSize(); i++) {
            if (visibleFields.getField(i).isVisible()) {
                totalWidth += visibleFields.getField(i).getWidth();
            }
        }    	
        ArrayList orderedColumns = new ArrayList();
        for (int i=0; i<visibleFields.getSize(); i++) {
            TableHeaderUIFacade.Column field = visibleFields.getField(i);
            orderedColumns.add(field);
        }
        Collections.sort(orderedColumns, new Comparator() {
            public int compare(Object o1, Object o2) {
                Column lhs = (Column) o1;
                Column rhs = (Column) o2;
                return lhs.getOrder()-rhs.getOrder();
            }
        });    	
        for (int i=0; i<orderedColumns.size(); i++){
            TableHeaderUIFacade.Column field = (Column) orderedColumns.get(i);
            addAttribute("id", field.getID(), attrs);
            addAttribute("name", field.getName(), attrs);
            addAttribute("width", field.getWidth()*100/totalWidth, attrs);
            addAttribute("visible", field.isVisible() ? "true" : "false", attrs);
            emptyElement("field", attrs, handler);
        }    	
    }
    protected void writeViews(UIFacade facade, TransformerHandler handler) throws SAXException {
        AttributesImpl attrs = new AttributesImpl();
        addAttribute("id", "task-table", attrs);
        startElement("view", attrs, handler);
        writeColumns(facade.getTaskTree().getVisibleFields(), handler);
        endElement("view", handler);

        addAttribute("id", "resource-table", attrs);
        startElement("view", attrs, handler);
        writeColumns(facade.getResourceTree().getVisibleFields(), handler);

        endElement("view", handler);
    }


    protected void writeTasks(TaskManager taskManager,
            final TransformerHandler handler) throws ExportException,
            SAXException {
        AttributesImpl attrs = new AttributesImpl();
        addAttribute("xslfo-path", "", attrs);
        addAttribute("title", i18n("tasksList"), attrs);
        addAttribute("name", i18n("name"), attrs);
        addAttribute("begin", i18n("start"), attrs);
        addAttribute("end", i18n("end"), attrs);
        addAttribute("milestone", i18n("meetingPoint"), attrs);
        addAttribute("progress", "%", attrs);
        addAttribute("assigned-to", i18n("human"), attrs);
        addAttribute("notes", i18n("notes"), attrs);
        addAttribute("duration", i18n("duration"), attrs);
        startPrefixedElement("tasks", attrs, handler);
        TaskVisitor visitor = new TaskVisitor() {
            AttributesImpl myAttrs = new AttributesImpl();
            protected String serializeTask(Task t, int depth) throws Exception {
                if (mySelectedTasks.isEmpty() || mySelectedTasks.contains(t)) {
                    addAttribute("selected", "true", myAttrs);
                }
                addAttribute("depth", depth, myAttrs);
                startPrefixedElement("task", myAttrs, handler);
                {
                    addAttribute("id", "tpd1", myAttrs);
                    int priority = t.getPriority();
                    if (priority<0 || priority>2) {
                        priority = 1;
                    }
                    final String[] priorities = new String[] {i18n("low"), i18n("normal"), i18n("hight")};
                    textElement("priority", myAttrs, priorities[priority], handler);
                }

                addAttribute("id", "tpd3", myAttrs);
                textElement("name", myAttrs, t.getName(), handler);

                addAttribute("id", "tpd4", myAttrs);                
                textElement("begin", myAttrs, t.getStart().toString(), handler);

                addAttribute("id", "tpd5", myAttrs);
                textElement("end", myAttrs, t.getEnd().toString(), handler);
                textElement("milestone", myAttrs, Boolean.valueOf(
                        t.isMilestone()).toString(), handler);

                addAttribute("id", "tpd7", myAttrs);
                textElement("progress", myAttrs, String.valueOf(t
                        .getCompletionPercentage()), handler);

                addAttribute("id", "tpd6", myAttrs);
                textElement("duration", myAttrs, String.valueOf(t.getDuration().getLength()), handler);

                {
                    ProjectResource coordinator = t.getAssignmentCollection().getCoordinator();
                    if (coordinator!=null) {
                        addAttribute("id", "tpd8", myAttrs);
                        textElement("coordinator", myAttrs, coordinator.getName(), handler);                		
                    }
                }
                StringBuffer usersS = new StringBuffer();
                ResourceAssignment[] assignments = t.getAssignments();
                if (assignments.length > 0) {
                    for (int j = 0; j < assignments.length; j++) {
                        addAttribute("resource-id", assignments[j].getResource().getId(), myAttrs);
                        emptyElement("assigned-resource", myAttrs, handler);
                        usersS.append(assignments[j].getResource().getName());
                        if (j<assignments.length-1) {
                            usersS.append(getAssignedResourcesDelimiter());
                        }
                    }
                } 

                addAttribute("id", "tpdResources", myAttrs);
                textElement("assigned-to", myAttrs, usersS.toString(), handler);
                if (t.getNotes()!=null && t.getNotes().length()>0) {
                    textElement("notes", myAttrs, t.getNotes(), handler);
                }
                if (t.getColor()!=null) {
                    textElement("color", myAttrs, getHexaColor(t.getColor()),
                            handler);
                }
                {
                    AttributesImpl attrs = new AttributesImpl();
                    CustomColumnsValues customValues = t.getCustomValues();
                    for (Iterator it = getCustomColumnStorage().getCustomColums().iterator();
                    it.hasNext();) {
                        CustomColumn nextColumn = (CustomColumn) it.next();
                        Object value = customValues.getValue(nextColumn.getName());
                        String valueAsString = value==null ? "" : value.toString();
                        addAttribute("id", nextColumn.getId(), attrs);
                        textElement("custom-field", attrs, valueAsString, handler);
                    }
                }
                endPrefixedElement("task", handler);
                return "";
            }
        };
        try {
            visitor.visit(taskManager);
        } catch (Exception e) {
            throw new ExportException("Failed to write tasks", e);
        }
        endPrefixedElement("tasks", handler);
    }

    protected String getAssignedResourcesDelimiter() {
        return " ";
    }

    protected void writeResources(ResourceManager resourceManager,
            TransformerHandler handler) throws SAXException {
        AttributesImpl attrs = new AttributesImpl();
        addAttribute("title", i18n("resourcesList"), attrs);
        addAttribute("name", i18n("colName"), attrs);
        addAttribute("role", i18n("colRole"), attrs);
        addAttribute("mail", i18n("colMail"), attrs);
        addAttribute("phone", i18n("colPhone"), attrs);
        startPrefixedElement("resources", attrs, handler);
        {
            List resources = resourceManager.getResources();

            // String
            // []function=RoleManager.Access.getInstance().getRoleNames();
            for (int i = 0; i < resources.size(); i++) {
                HumanResource p = (HumanResource) resources.get(i);
                addAttribute("id", p.getId(), attrs);
                startPrefixedElement("resource", attrs, handler);
                addAttribute("id", "0", attrs);
                textElement("name", attrs, p.getName(), handler);
                addAttribute("id", "1", attrs);
                textElement("role", attrs, p.getRole().getName(), handler);
                addAttribute("id", "2", attrs);
                textElement("mail", attrs, p.getMail(), handler);
                addAttribute("id", "3", attrs);
                textElement("phone", attrs, p.getPhone(), handler);

                List/*<CustomProperty>*/ customFields = p.getCustomProperties();
                System.err.println("custom fields: "+customFields);
                for (int j=0; j<customFields.size(); j++) {
                    CustomProperty nextProperty = (CustomProperty) customFields.get(j);
                    addAttribute("id", nextProperty.getDefinition().getID(), attrs);
                    String value = nextProperty.getValueAsString();
                    textElement("custom-field", attrs, value, handler);
                }
                endPrefixedElement("resource", handler);
            }

        }
        endPrefixedElement("resources", handler);

    }

    protected static String getHexaColor(java.awt.Color color) {
        StringBuffer out = new StringBuffer();
        out.append("#");
        if (color.getRed() <= 15) {
            out.append("0");
        }
        out.append(Integer.toHexString(color.getRed()));
        if (color.getGreen() <= 15) {
            out.append("0");
        }
        out.append(Integer.toHexString(color.getGreen()));
        if (color.getBlue() <= 15) {
            out.append("0");
        }
        out.append(Integer.toHexString(color.getBlue()));

        return out.toString();
    }

    public static class URLUTF8Encoder
    {

        final static String[] hex = {
            "%00", "%01", "%02", "%03", "%04", "%05", "%06", "%07",
            "%08", "%09", "%0a", "%0b", "%0c", "%0d", "%0e", "%0f",
            "%10", "%11", "%12", "%13", "%14", "%15", "%16", "%17",
            "%18", "%19", "%1a", "%1b", "%1c", "%1d", "%1e", "%1f",
            "%20", "%21", "%22", "%23", "%24", "%25", "%26", "%27",
            "%28", "%29", "%2a", "%2b", "%2c", "%2d", "%2e", "%2f",
            "%30", "%31", "%32", "%33", "%34", "%35", "%36", "%37",
            "%38", "%39", "%3a", "%3b", "%3c", "%3d", "%3e", "%3f",
            "%40", "%41", "%42", "%43", "%44", "%45", "%46", "%47",
            "%48", "%49", "%4a", "%4b", "%4c", "%4d", "%4e", "%4f",
            "%50", "%51", "%52", "%53", "%54", "%55", "%56", "%57",
            "%58", "%59", "%5a", "%5b", "%5c", "%5d", "%5e", "%5f",
            "%60", "%61", "%62", "%63", "%64", "%65", "%66", "%67",
            "%68", "%69", "%6a", "%6b", "%6c", "%6d", "%6e", "%6f",
            "%70", "%71", "%72", "%73", "%74", "%75", "%76", "%77",
            "%78", "%79", "%7a", "%7b", "%7c", "%7d", "%7e", "%7f",
            "%80", "%81", "%82", "%83", "%84", "%85", "%86", "%87",
            "%88", "%89", "%8a", "%8b", "%8c", "%8d", "%8e", "%8f",
            "%90", "%91", "%92", "%93", "%94", "%95", "%96", "%97",
            "%98", "%99", "%9a", "%9b", "%9c", "%9d", "%9e", "%9f",
            "%a0", "%a1", "%a2", "%a3", "%a4", "%a5", "%a6", "%a7",
            "%a8", "%a9", "%aa", "%ab", "%ac", "%ad", "%ae", "%af",
            "%b0", "%b1", "%b2", "%b3", "%b4", "%b5", "%b6", "%b7",
            "%b8", "%b9", "%ba", "%bb", "%bc", "%bd", "%be", "%bf",
            "%c0", "%c1", "%c2", "%c3", "%c4", "%c5", "%c6", "%c7",
            "%c8", "%c9", "%ca", "%cb", "%cc", "%cd", "%ce", "%cf",
            "%d0", "%d1", "%d2", "%d3", "%d4", "%d5", "%d6", "%d7",
            "%d8", "%d9", "%da", "%db", "%dc", "%dd", "%de", "%df",
            "%e0", "%e1", "%e2", "%e3", "%e4", "%e5", "%e6", "%e7",
            "%e8", "%e9", "%ea", "%eb", "%ec", "%ed", "%ee", "%ef",
            "%f0", "%f1", "%f2", "%f3", "%f4", "%f5", "%f6", "%f7",
            "%f8", "%f9", "%fa", "%fb", "%fc", "%fd", "%fe", "%ff"
        };

        /**
         * Encode a string to the "x-www-form-urlencoded" form, enhanced
         * with the UTF-8-in-URL proposal. This is what happens:
         *
         * <ul>
         * <li><p>The ASCII characters 'a' through 'z', 'A' through 'Z',
         *        and '0' through '9' remain the same.
         *
         * <li><p>The unreserved characters - _ . ! ~ * ' ( ) remain the same.
         *
         * <li><p>The space character ' ' is converted into a plus sign '+'.
         *
         * <li><p>All other ASCII characters are converted into the
         *        3-character string "%xy", where xy is
         *        the two-digit hexadecimal representation of the character
         *        code
         *
         * <li><p>All non-ASCII characters are encoded in two steps: first
         *        to a sequence of 2 or 3 bytes, using the UTF-8 algorithm;
         *        secondly each of these bytes is encoded as "%xx".
         * </ul>
         *
         * @param s The string to be encoded
         * @return The encoded string
         */
        public static String encode(String s)
        {
            StringBuffer sbuf = new StringBuffer();
            int len = s.length();
            for (int i = 0; i < len; i++) {
                int ch = s.charAt(i);
                if ('A' <= ch && ch <= 'Z') {		// 'A'..'Z'
                    sbuf.append((char)ch);
                } else if ('a' <= ch && ch <= 'z') {	// 'a'..'z'
                    sbuf.append((char)ch);
                } else if ('0' <= ch && ch <= '9') {	// '0'..'9'
                    sbuf.append((char)ch);
                } else if (ch == ' ') {			// space
                    sbuf.append('+');
                } else if (ch == '-' || ch == '_'		// unreserved
                    || ch == '.' || ch == '!'
                        || ch == '~' || ch == '*'
                            || ch == '\'' || ch == '('
                                || ch == ')') {
                    sbuf.append((char)ch);
                } else if (ch <= 0x007f) {		// other ASCII
                    sbuf.append(hex[ch]);
                } else if (ch <= 0x07FF) {		// non-ASCII <= 0x7FF
                    sbuf.append(hex[0xc0 | (ch >> 6)]);
                    sbuf.append(hex[0x80 | (ch & 0x3F)]);
                } else {					// 0x7FF < ch <= 0xFFFF
                    sbuf.append(hex[0xe0 | (ch >> 12)]);
                    sbuf.append(hex[0x80 | ((ch >> 6) & 0x3F)]);
                    sbuf.append(hex[0x80 | (ch & 0x3F)]);
                }
            }
            return sbuf.toString();
        }

    }

}