/*
 * $Id: BasicFileLocator.java 220 2007-07-16 10:32:15Z sugimotokenichi $
 * Copyright (C) 2005 SUGIMOTO Ken-ichi
 * 作成日： 2005/4/3
 */

package feat2.config;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * ファイルの場所を表すクラス。
 */
public class BasicFileLocator implements FileLocator {

    private File file;
    private FileLocator rootLocation;

    /**
     *
     * @param file
     * @throws IllegalArgumentException 引数がnull
     */
    public BasicFileLocator(File file) throws IllegalArgumentException {
        if ( file == null )
            throw new IllegalArgumentException("file:null");
        this.file = file;
        this.rootLocation = this;
    }

    protected BasicFileLocator(File file, FileLocator rootLocation) {
        this(file);
        if ( rootLocation == null )
            this.rootLocation = this;
        else
            this.rootLocation = rootLocation;
    }

    public InputStream openInputStream() throws IOException {
        return new FileInputStream(file);
    }

    public String getURIString() {
        return file.toURI().toASCIIString();
    }

    public FileLocator newLocation(String relativePath) throws IllegalArgumentException {
        if ( relativePath == null )
            return this;

        if ( relativePath.startsWith("/") )
            throw new IllegalArgumentException("\""+relativePath+"\" '/'で始まるパスは指定できない");
        if ( relativePath.startsWith(".") )
        	throw new IllegalArgumentException("\""+relativePath+"\" ディレクトリ名の先頭に'.'は使用できない");
        if ( relativePath.indexOf("..") > -1 )
            throw new IllegalArgumentException("\""+relativePath+"\" 上位のディレクトリは指定できない");

        if ( file.isFile() ) {
            return new BasicFileLocator(new File(file.getParentFile(), relativePath), rootLocation);
        }
        else {
            return new BasicFileLocator(new File(file, relativePath), rootLocation);
        }

    }

    public FileLocator rootLocation() {
        return rootLocation;
    }

    public boolean exists() {
        return file.exists();
    }

    public String getFilename() {
        if ( file.isFile() )
            return file.getName();
        else
        	return null;
    }

    public long getLastModified() {
        return file.lastModified();
    }

    public boolean equals(Object o) {
        BasicFileLocator loc = (BasicFileLocator)o;
        boolean ret = file.equals(loc.file);
        if ( rootLocation != this )
            ret = ret && rootLocation.equals(loc.rootLocation);
        return ret;
    }

    public String toString() {
        StringBuffer buf = new StringBuffer();
        if ( rootLocation != this ) {
            buf.append("<").append(rootLocation.toString()).append(">");
        }
        buf.append(file.getPath());
        return buf.toString();
    }
}
