package org.wikiwebserver.sync;

import java.io.File;
import java.io.Serializable;
import java.text.DateFormat;

public class FileItem implements Serializable {

    private static final long serialVersionUID = 1L;

    public static enum State { UNKNOWN, EXISTS, DELETED, MODIFIED, NOT_MODIFIED };
    public static enum Type { FILE, DIRECTORY, UNREADABLE };
    
    private final String relPath;
    
    private long lastModified;
    private long length;
    private Type type;
    private int site = -1;
    private State state;
    
    public FileItem(File file, File base) {
        this(file.getAbsolutePath().substring(base.getAbsolutePath().length()+1));
        if (file.canRead()) {
            if (file.isDirectory()) setType(Type.DIRECTORY);  
            else setType(Type.FILE);        
        } else {
            setType(Type.UNREADABLE);
        }
        
        setLastModified(file.lastModified());
        setLength(file.length());        
    }
    
    public FileItem(String relPath) {
        relPath = relPath.replace('\\', '/');
        this.relPath = relPath;
    }
    
    public FileItem clone() {
        FileItem cloned = new FileItem(getRelPath());
        cloned.setType(getType());
        cloned.setLastModified(getLastModified());
        cloned.setLength(getLength());
        cloned.setState(getState());
        cloned.setSite(getSite());
        return cloned;
    }
    
    public void setState(State state) {
        this.state = state;
    }

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

    public long getLength() {
        return this.length;
    }

    public int getSite() {
        return this.site;
    }

    public State getState() {
        return this.state;
    }

    public String getRelPath() {
        return this.relPath;
    }

    public void setLastModified(long lastModified) {
        this.lastModified = lastModified;
    }

    public void setLength(long length) {
        this.length = length;
    }

    public void setSite(int site) {
        this.site = site;
    }    
    
    public int hashCode() {
        return getRelPath().hashCode();
    }
    
    public String toString() {
        String s =  "Location " + getSite() + " ";
        
        if (getState() != State.UNKNOWN) s += getState() + " ";
        
        s += getType() + " \'" + getRelPath() + "\'";
        
        if (getState() == State.UNKNOWN) s += " last modified ";
        if (getState() == State.DELETED)  s += " after ";
        if (getState() == State.EXISTS) s += " on ";
        if (getState() == State.MODIFIED) s += " on ";
        
        s += DateFormat.getInstance().format(getLastModified());
        
        return s;
    }

    public Type getType() {
        return this.type;
    }

    public void setType(Type type) {
        this.type = type;
    }
}

