package com.codice.client.glassfs;

import java.lang.*;
import java.io.*;
import java.util.*;

import com.codice.client.common.*;
import com.codice.client.commands.*;
import com.codice.client.basecommands.*;

import com.codice.cm.common.*;

class FileCache {
    private String mBasePath;

    FileCache() {
        mBasePath = Path.combine(path.getDirectoryName(
            this.getClass().getProtectionDomain().getCodeSource()
                .getLocation().getPath()),
            "filecache");
        File d = new File(mBasePath);
        if (!d.isDirectory())
            d.mkdir();
    }

    public String hashToHex(String hash) {
        StringBuilder hexString = new StringBuilder(hash.length);

        for (int i = 0; i < hash.length; i++) {
            char c = (char)hash[i];
            byte b = (byte) c;
            hexString.append(String.format("%02X", b));
        }

        return hexString.toString();
    }

    String GetFile(RepositoryInfo repInfo, RevisionInfo revInfo, PlasticAPI api) {
        String hash = hashToHex(revInfo.hash);

        String subdir = Path.Combine(mBasePath, hash.substring(0, 1).concat(hash.substring(1, 2)));

        File d = new File(subdir);
        if (!d.isDirectory())
            d.mkdir();

        String file = Path.Combine(subdir, hash);

        File f = new File(file);
        if (f.exists())
            return file;

        api.getFile(repInfo, revInfo, file);

        return file;
    }
}
