/*
 * JSPTem - use jsp's for all your templating!
 * Copyright (c) 2006, Paul Tuckey
 * All rights reserved.
 *
 * JSPTem is based on GNUJSP (Copyright (C) 1999, Yaroslav Faybishenko <yaroslav@cs.berkeley.edu>)
 *
 * Each copy or derived work must preserve the copyright notice and this
 * notice unmodified.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */
package org.tuckey.jsptem;

import java.net.URL;
import java.util.StringTokenizer;

public class JspParserContext {

    // The virtual path of this JSP page
    private String jspPageURI = null;
    private static String fileSeparator =
            System.getProperty("file.separator");
    private static String fileSeparators = "/" + fileSeparator;
    private static boolean pathDebug = false;
    private static boolean generateXML = false;

    private static boolean hasCaseInsensitiveFilenames = false;

    public static void setCaseInsensitiveFilenames(boolean b) {
        hasCaseInsensitiveFilenames = b;
    }

    public static boolean getCaseInsensitiveFilenames() {
        return hasCaseInsensitiveFilenames;
    }

    // The actual path of the JSP file
    private URL jspPageURL = null;

    // FIXME: remove public
    public JspParserContext(String jspURI, URL jspURL) {
        this.jspPageURL = jspURL;
        this.jspPageURI = jspURI;
    }

    public void setPathDebug(boolean b) {
        pathDebug = b;
    }

    public void setGenerateXML(boolean b) {
        generateXML = b;
    }

    public boolean getGenerateXML() {
        return generateXML;
    }

    // split URL path at "/" or file.separator
    private static String [] splitURL(String path) {
        StringTokenizer st = new StringTokenizer(path, fileSeparators);
        int numParts = st.countTokens();
        String parts[] = new String[numParts];
        int i = 0;

        while (st.hasMoreTokens()) {
            parts[i++] = (String) st.nextElement();
        }

        return parts;
    }

    /**
     * concat parts from start not including end
     * Note: return value does not start with fileSeparator
     */
    private static String concatParts(String parts[], int start, int end) {
        StringBuffer sb = new StringBuffer(200);
        boolean first = true;
        while (start < end) {
            if (!first) {
                sb.append((fileSeparator.charAt(0) == '\\') ? "/" : fileSeparator);
            } else {
                first = false;
            }
            sb.append(parts[start++]);
        }
        return sb.toString();
    }

    // example: oldURI: /people/wes/testsuite/wes.jsp
    //          newURI: /people/wes/dir1/file.jsp --> ../dir1/file.jsp
    //                  /people/wes/testsuite/file.jsp --> file.jsp
    //                  /people/wes/testsuite/dir1/file.jsp --> dir1/file.jsp
    private static String getRelativePath(String[] oldURI, String[] newURI) {
        int len1 = oldURI.length;
        int len2 = newURI.length;
        int minlen = (len1 < len2) ? len1 : len2;

        // First see how much they share in common, starting from index 0

        int i = 0;
        while ((i < minlen)
                && ((hasCaseInsensitiveFilenames && oldURI[i].equalsIgnoreCase(newURI[i]))
                || oldURI[i].equals(newURI[i]))) i++;

        // variable i represents the number of shared path parts.
        int left = len1 - i;
        StringBuffer retval = new StringBuffer();
        // add (left - 1) copies of "../"
        while (--left > 0) {
            retval.append("../");
        }
        retval.append(concatParts(newURI, i, len2));
        return retval.toString();
    }

    /**
     * try to calculate URL of given path relative
     * to current JSP page
     */
    public URL getRealPath(String relativeURLPath) {
        return getRealPath(jspPageURI,
                jspPageURL.getFile(),
                relativeURLPath);
    }

    /**
     * try to calculate URL of given path relative
     * to current JSP page based on known
     * pair jspURI/jspURL
     */
    public static URL getRealPath(String jspURI,
                                  String jspURLFile,
                                  String relativeURLPath) {
        /*
         example:
         jspURI: /testsuite/dir1/x.jsp
         jspURL: file:/usr/local/www/doc/testsuite/dir1/x.jsp
         jspURLFile: /usr/local/www/doc/testsuite/dir1/x.jsp
         relPath: ../dir2/y.jsp

         algorithmus:
         baseDirURL: jspURL without common_tail(jspURI, jspURL)
         baseRelURL: common_tail(jspURI, jspURL) as URL
         relURL: URL(baseRelURL, relativeURLPath)
         URL: URL(baseDirURL, relative_path(relURL))

         example:
         baseDirURL: file:/usr/local/www/doc
         baseRelURL: file:/testsuite/dir1/x.jsp
         relURL: (/)testsuite/dir2/y.jsp
         URL: file:/usr/local/www/doc/testsuite/dir2/y.jsp

         Note: on windows the file url may have a different case
               than the uri
        */

        String uriparts[] = splitURL(jspURI);
        String urlparts[] = splitURL(jspURLFile);

        // WWB 20 Nov 1999: First make relativeURLPath relative if
        // possible to avoid problems with different mappings like ~wes
        // Note that you can't (in JServ) do an include/forward from
        // a different mapping, the info we need just doesn't exist.

        // See what's common between jspURI and relativeURI
        if (pathDebug) System.err.println("JspParserContext: relativeURLPath1=" + relativeURLPath);
        if (relativeURLPath.startsWith("/")) {
            relativeURLPath = getRelativePath(uriparts, splitURL(relativeURLPath));
            if (pathDebug) System.err.println("JspParserContext: relativeURLPath1=" + relativeURLPath);
        }

        int urilen = uriparts.length;
        int urllen = urlparts.length;

        int maxlen = Math.min(urilen, urllen);

        if (pathDebug) {
            System.err.println("JspParserContext: jspURI=" + jspURI
                    + "\n\tjspURL= " + jspURLFile
                    + "\n\tmaxlen= " + maxlen);
        }

        // strange url/uri ...
        if (maxlen == 0)
            return null;

        int i = 1;
        // same file name?
        if (hasCaseInsensitiveFilenames) {
            if (!uriparts[urilen - 1].equalsIgnoreCase(urlparts[urllen - 1]))
                return null;
            // find common tail
            while (i < maxlen && uriparts[urilen - 1 - i]
                    .equalsIgnoreCase(urlparts[urllen - 1 - i])) {
                i++;
            }
        } else {
            if (!uriparts[urilen - 1].equals(urlparts[urllen - 1]))
                return null;
            // find common tail
            while (i < maxlen && uriparts[urilen - 1 - i]
                    .equals(urlparts[urllen - 1 - i])) {
                i++;
            }
        }

        int numCommon = i - 1;

        URL result;
        try {
            URL baseDirURL =
                    new URL("file:/"
                            + concatParts(urlparts,
                            0,
                            urllen - numCommon - 1)
                            + fileSeparator
                    );

            URL baseRelURL =
                    new URL("file:/"
                            + concatParts(urlparts,
                            urllen - numCommon - 1,
                            urllen));

            URL relURL = new URL(baseRelURL, relativeURLPath);
            String file = relURL.getFile();

            result = new URL(baseDirURL,
                    // strip leading fileSeparator
                    file.substring(1)
            );

            if (pathDebug) {
                System.err.println("JspParserContext: jspURL:" + jspURLFile
                        + "\n\tbaseDirURL: " + baseDirURL
                        + "\n\tbaseRelURL: " + baseRelURL
                        + "\n\trelURL: " + relURL
                        + "\n\tresult: " + result);
            }

            return result;
        } catch (java.net.MalformedURLException e) {
            System.err.println("JspParserContext: internal problem: " + e);
        }
        return null;
    }
}
