package cz.kamma.kfmanager.model;

import javax.swing.Icon;
import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Model representing a file or directory for display in the table
 */
public class FileItem {
    
    private final File file;
    private final String name;
    private final long size;
    private final Date modified;
    private final boolean isDirectory;
    private final Icon icon;
    private boolean marked;
    private String displayPath;

    public FileItem(File file) {
        this(file, null);
    }

    public FileItem(File file, String displayPath) {
        this.file = file;
        this.name = file.getName();
        this.size = file.length();
        this.modified = new Date(file.lastModified());
        this.isDirectory = file.isDirectory();
        this.marked = false;
        this.displayPath = displayPath;

        // Load icon from system
        this.icon = FileSystemView.getFileSystemView().getSystemIcon(file);
    }

    public File getFile() {
        return file;
    }

    public String getName() {
        return name;
    }

    public String getFormattedSize() {
        if (isDirectory) {
            return "<DIR>";
        }
        return formatSize(size);
    }

    public long getSize() {
        return size;
    }

    public String getFormattedDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm");
        return sdf.format(modified);
    }

    public Date getModified() {
        return modified;
    }

    public boolean isDirectory() {
        return isDirectory;
    }

    public Icon getIcon() {
        return icon;
    }

    public String getPath() {
        return displayPath != null ? displayPath : file.getAbsolutePath();
    }
    
    public boolean isMarked() {
        return marked;
    }
    
    public void setMarked(boolean marked) {
        this.marked = marked;
    }
    
    public void toggleMarked() {
        this.marked = !this.marked;
    }
    
    /**
    * Format file size into a human-readable string
     */
    private String formatSize(long size) {
        if (size < 1024) {
            return size + " B";
        } else if (size < 1024 * 1024) {
            return String.format("%.1f KB", size / 1024.0);
        } else if (size < 1024 * 1024 * 1024) {
            return String.format("%.1f MB", size / (1024.0 * 1024.0));
        } else {
            return String.format("%.1f GB", size / (1024.0 * 1024.0 * 1024.0));
        }
    }
}
