package jp.sourceforge.projects.ee2e.core.typeset;
import org.eclipse.core.resources.*;
import org.eclipse.ui.*;
import org.eclipse.core.runtime.*;
import jp.sourceforge.projects.ee2e.core.*;

import java.io.IOException;
import java.net.*;

/**
 * To change this generated comment edit the template variable "typecomment":
 * Window&gt;Preferences&gt;Java&gt;Templates.
 * To enable and disable the creation of type comments go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation.
 *
 * @author Toshikazu Ando [ ando@park.ruru.ne.jp ]
 */
public class EE2EReasonedFile {

    /**
     * Constructor for EE2EReasonedFile.
     */
    public EE2EReasonedFile() {
        super();
    }
    public IFile getFile(String selectString, java.io.File parent)
        throws PartInitException {
        if ((selectString == null) || (selectString.equals(""))) {
            throw new PartInitException("No region!");
        }
        if (this.isCheckNumber(0, selectString)) {
            IFileEditorInput editorInput = getIFileEditorInput();
            return editorInput.getFile();
        }
        if (parent == null) {
            parent = new java.io.File(".");
        }
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < selectString.length(); i++) {
            char ch = selectString.charAt(i);
            if ((ch == '$')
                || (ch == '(')
                || (ch == ')')
                || (ch == '{')
                || (ch == '}')
                || (ch == '[')
                || (ch == ']')
                || (ch == '*')
                || (ch == '\"')
                || (ch == '\'')
                || (ch == '!')
                || ((ch == ':') && (!this.checkColonFolder(buffer.toString())))
                || (ch == ';')) {
                if (0 < buffer.length()) {
                    break;
                }
                continue;
            }
            if (ch == '=') {
                buffer = new StringBuffer();
                continue;
            }
            if ((ch == '\t')
                || (ch == '\n')
                || (ch == '\r')
                || (ch == '#')
                || (ch == '?')
                || (ch == '&')) {
                break;
            }
            buffer.append(ch);
        }
        boolean flag = false;
        int limmit = -1;
        for (int i = 0; i < buffer.length(); i++) {
            if (buffer.charAt(i) != ' ') {
                break;
            }
            limmit = i;
        }
        if (0 <= limmit) {
            buffer = buffer.replace(0, limmit + 1, "");
        }
        limmit = buffer.length();
        for (int i = buffer.length() - 1; 0 < i; i--) {
            if (buffer.charAt(i) != ' ') {
                break;
            }
            flag = true;
            limmit = i;
        }
        String string;
        if (flag) {
            string = buffer.substring(0, limmit);
        } else {
            string = buffer.toString();
        }
        if ((parent != null) && (string != null) && (string.indexOf(".") < 0)) {
            int extPos = parent.getName().lastIndexOf(".");
            if ( 1 < extPos) {
                string = string + parent.getName().substring(extPos);
            }
        }
        //
        return getFileReal(string, parent);
    }
    public boolean checkColonFolder(String string) {
        if ((string == null) || (string.length() <= 0)) {
            return false;
        }
        if ((string.length() == 1)
            || string.equals("http")
            || string.equals("ftp")) {
            return true;
        }
        return false;
    }
    protected IFile getFileReal(String string, java.io.File parent)
        throws PartInitException {
        //
        IFile anserFile;
        //
        StringBuffer errorMessage = new StringBuffer();
        //
        anserFile = this.getFileURL(string, errorMessage);
        if (anserFile != null) {
            return anserFile;
        }
        anserFile = this.getFileOneMoreChance(string, parent, errorMessage);
        if (anserFile != null) {
            return anserFile;
        }
        String nextString = string;
        java.io.File workFile = new java.io.File(string);
        nextString = workFile.getName();
        if (!string.equals(nextString)) {
            anserFile =
                this.getFileOneMoreChance(nextString, parent, errorMessage);
            if (anserFile != null) {
                return anserFile;
            }
        }
        parent = parent.getParentFile();
        if (parent == null) {
            parent = new java.io.File(".");
        }
        anserFile = this.getSearchFile(nextString, parent, 5);
        if (anserFile != null) {
            return anserFile;
        }
        parent = parent.getParentFile();
        if (parent != null) {
            anserFile = this.getSearchFile(nextString, parent, 4);
            if (anserFile != null) {
                return anserFile;
            }
        }
        throw new PartInitException("Not found!!\n" + errorMessage.toString());
    }
    protected IFile getFileURL(String string, StringBuffer errorMessage) {
        IWorkspace iWorkSpase = ResourcesPlugin.getWorkspace();
        IWorkspaceRoot iWorkspaceRoot = iWorkSpase.getRoot();
        IPath appendPath;
        IFile anserFile;
        boolean flag;
        int limmit = 0;
        String urlToString;
        try {
            java.net.URL url = new java.net.URL(string);
            urlToString = url.getFile();
        } catch (MalformedURLException e) {
            urlToString = string;
        }
        flag = false;
        for (int i = 0; i < urlToString.length(); i++) {
            limmit = i;
            if (urlToString.charAt(i) != '/') {
                break; // vs. /c:/aaa/bbb/
            }
            flag = true;
        }
        if (flag) {
            urlToString = urlToString.substring(limmit);
        }
        if (urlToString == null) {
            return null;
        }
        try {
            appendPath =
                new Path((new java.io.File(urlToString)).getCanonicalPath());
        } catch (IOException e) {
            appendPath = new Path(urlToString);
        }
        anserFile = iWorkspaceRoot.getFileForLocation(appendPath);
        errorMessage.append(appendPath.toFile().toString() + "\n");
        if ((anserFile != null) && anserFile.exists()) {
            return anserFile;
        }
        IWorkspace workSpace = ResourcesPlugin.getWorkspace();
        java.io.File file = workSpace.getRoot().getLocation().toFile();
        file = new java.io.File(file, urlToString);
        try {
            appendPath = new Path(appendPath.toFile().getCanonicalPath());
        } catch (IOException e) {
            appendPath = new Path(file.toString());
        }
        anserFile = iWorkspaceRoot.getFileForLocation(appendPath);
        errorMessage.append(appendPath.toFile().toString() + "\n");
        if ((anserFile != null) && anserFile.exists()) {
            return anserFile;
        }
        return null;
    }
    protected IFile getFileOneMoreChance(
        String string,
        java.io.File parent,
        StringBuffer errorMessage) {
        IPath appendPath;
        IFile anserFile;
        appendPath = new Path(string);
        IWorkspace iWorkSpase = ResourcesPlugin.getWorkspace();
        IWorkspaceRoot iWorkspaceRoot = iWorkSpase.getRoot();
        anserFile = iWorkspaceRoot.getFileForLocation(appendPath);
        errorMessage.append(appendPath.toFile().toString() + "\n");
        if ((anserFile != null) && anserFile.exists()) {
            return anserFile;
        }
        if (parent != null) {
            java.io.File base = new java.io.File(parent, string);
            try {
                appendPath = new Path(base.getCanonicalPath());
            } catch (IOException e1) {
                appendPath = new Path(base.toString());
            }
            anserFile = iWorkspaceRoot.getFileForLocation(appendPath);
            errorMessage.append(appendPath.toFile().toString() + "\n");
            if ((anserFile != null) && anserFile.exists()) {
                return anserFile;
            }
        }
        java.io.File file = iWorkspaceRoot.getLocation().toFile();
        file = new java.io.File(file, string);
        try {
            appendPath = new Path(file.getCanonicalPath());
        } catch (IOException e1) {
            appendPath = new Path(file.toString());
        }
        anserFile = iWorkspaceRoot.getFileForLocation(appendPath);
        errorMessage.append(appendPath.toFile().toString() + "\n");
        if ((anserFile != null) && anserFile.exists()) {
            return anserFile;
        }
        //
        anserFile = this.getActiveFile(string);
        errorMessage.append(appendPath.toFile().toString() + "\n");
        if ((anserFile != null) && anserFile.exists()) {
            return anserFile;
        }
        IFileEditorInput iFileEditorInput = this.getIFileEditorInput();
        if (iFileEditorInput != null) {
            IContainer iContainer = iFileEditorInput.getFile().getParent();
            String[] segments = iContainer.getFullPath().segments();
            String relativityTarget =
                iWorkspaceRoot.getLocation().toFile().toString();
            for (int i = 0; i < segments.length; i++) {
                relativityTarget =
                    relativityTarget + java.io.File.separator + segments[i];
                file = new java.io.File(relativityTarget);
                file = new java.io.File(file, string);
                try {
                    appendPath = new Path(file.getCanonicalPath());
                } catch (IOException e2) {
                    appendPath = new Path(file.toString());
                }
                try {
                    anserFile = iWorkspaceRoot.getFileForLocation(appendPath);
                    errorMessage.append(appendPath.toFile().toString() + "\n");
                    if ((anserFile != null) && anserFile.exists()) {
                        return anserFile;
                    }
                } catch (RuntimeException aException) {
                    EE2EDebug.printf(
                        5,
                        "path="
                            + relativityTarget
                            + " e=\""
                            + aException.getMessage()
                            + "\"");
                }
            }
        }
        return null;
    }
    protected IFile getSearchFile(
        String string,
        java.io.File parent,
        int deep) {
        if (deep <= 0) {
            return null;
        }
        if (!parent.isDirectory()) {
            return null;
        }
        java.io.File list[] = parent.listFiles();
        IFile anserFile;
        IWorkspace iWorkSpase = ResourcesPlugin.getWorkspace();
        IWorkspaceRoot iWorkspaceRoot = iWorkSpase.getRoot();
        for (int i = 0; i < list.length; i++) {
            if (list[i].isFile()) {
                String ans = list[i].getName();
                if (ans.equalsIgnoreCase(string)) {
                    IPath appendPath;
                    appendPath = new Path(list[i].toString());
                    try {
                        anserFile =
                            iWorkspaceRoot.getFileForLocation(appendPath);
                        if ((anserFile != null) && anserFile.exists()) {
                            return anserFile;
                        }
                    } catch (RuntimeException aException) {
                        /*EMPTY*/
                    }
                }
            } else if (list[i].isDirectory()) {
                anserFile = this.getSearchFile(string, list[i], deep - 1);
                if ((anserFile != null) && anserFile.exists()) {
                    return anserFile;
                }
            }
        }
        return null;
    }
    protected boolean isCheckNumber(int point, String selectString) {
        this.setLineNumber(0);
        for (int i = point; i < selectString.length(); i++) {
            if ((' ' == selectString.charAt(i))
                || ('\t' == selectString.charAt(i))) {
                continue;
            }
            if (('0' <= selectString.charAt(i))
                && (selectString.charAt(i) <= '9')) {
                this.setLineNumber(
                    (this.getLineNumber() * 10)
                        + ((int) selectString.charAt(i))
                        - ((int) '0'));
                continue;
            }
            break;
        }
        return (0 < this.getLineNumber());
    }
    protected IFile getActiveFile(String target) {
        IFileEditorInput fileInput = getIFileEditorInput();
        if (fileInput == null) {
            return null;
        }
        java.io.File file =
            fileInput.getFile().getParent().getLocation().toFile();
        file = new java.io.File(file, target);
        IPath appendPath = new Path(file.toString());
        IWorkspace iWorkSpase = ResourcesPlugin.getWorkspace();
        IWorkspaceRoot iWorkspaceRoot = iWorkSpase.getRoot();
        IFile anserFile = iWorkspaceRoot.getFileForLocation(appendPath);
        return anserFile;
    }
    protected IFileEditorInput getIFileEditorInput() {
        IEditorPart activeEditor =
            PlatformUI
                .getWorkbench()
                .getActiveWorkbenchWindow()
                .getActivePage()
                .getActiveEditor();
        if (activeEditor == null) {
            return null;
        }
        IEditorInput editorInput = activeEditor.getEditorInput();
        if (!(editorInput instanceof IFileEditorInput)) {
            return null;
        }
        return (IFileEditorInput) editorInput;
    }
    public int getLineNumber() {
        return this.lineNumber;
    }
    public void setLineNumber(int lineNumber) {
        this.lineNumber = lineNumber;
    }
    private int lineNumber;
}
