package com.jscape.inet.sftp;

import com.jscape.util.file.PosixFilePermissions;
import com.jscape.util.file.UnixFileType;

import java.util.Comparator;

import static com.jscape.util.Parameters.assertNotNull;

/**
 * @author Alex Usun
 */
public class PathInfo {

    public final String name;
    public final UnixFileType type;
    public final long size;
    public final String owner;
    public final String group;
    public final PosixFilePermissions permissions;
    public final long accessTime;
    public final long modificationTime;

    public PathInfo(String name, UnixFileType type, long size, String owner, String group, PosixFilePermissions permissions, long accessTime, long modificationTime) {
        assertNotNull(name);
        this.name = name;

        assertNotNull(type);
        this.type = type;

        this.size = size;
        this.owner = owner;
        this.group = group;
        this.permissions = permissions;
        this.accessTime = accessTime;
        this.modificationTime = modificationTime;
    }

    public boolean directory() {
        return this.type == UnixFileType.DIRECTORY || this.type == UnixFileType.SYMBOLIC_LINK;
    }
    
    public boolean link() {
        return this.type == UnixFileType.SYMBOLIC_LINK;
    }

    public boolean readable() {
        return this.permissions != null && this.permissions.ownerCanRead;
    }

    public boolean writable() {
        return this.permissions != null && this.permissions.ownerCanWrite;
    }

    @Override
    public String toString() {
        return "PathInfo {"
               + "name='" + this.name + '\''
               + ", type=" + this.type
               + ", size=" + this.size
               + ", owner='" + this.owner + '\''
               + ", group='" + this.group + '\''
               + ", permissions=" + this.permissions
               + ", accessTime=" + this.accessTime
               + ", modificationTime=" + this.modificationTime
               + '}';
    }

    public static class NaturalComparator
            implements Comparator<PathInfo> {

        public int compare(PathInfo leftPath, PathInfo rightPath) {
            if (leftPath.directory() && !rightPath.directory()) {
                return -1;
            } else if (rightPath.directory() && !leftPath.directory()) {
                return 1;
            } else {
                return leftPath.name.compareTo(rightPath.name);
            }
        }
    }
}
