package info.knacki.pass.git;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

public class GitLocal {
    final private static Logger log = Logger.getLogger(GitLocal.class.getName());
    final private Map<String, String> cache;

    public GitLocal(File file) {
        cache = new HashMap<>();
        BufferedReader in;

        try {
            in = new BufferedReader(new FileReader(file));
        }
        catch (FileNotFoundException e) {
            return;
        }
        String line;
        try {
            while ((line = in.readLine()) != null) {
                int lineSep = line.indexOf(' ');
                if (lineSep > -1) {
                    cache.put(line.substring(lineSep +1), line.substring(0, lineSep));
                }
            }
            in.close();
        }
        catch (IOException e) {
            log.log(Level.WARNING, e.getMessage(), e);
        }
    }

    public String GetHash(String key, String defaultValue) {
        String res = cache.get(key);
        return res == null ? defaultValue : res;
    }

    public void SetHash(String filename, String hash) {
        cache.put(filename, hash);
    }

    public Set<String> FileNames() {
        return cache.keySet();
    }

    public GitLocal remove(String filename) {
        cache.remove(filename);
        return this;
    }

    public void Write(File f) {
        try {
            f.createNewFile();
            FileWriter writer = new FileWriter(f);
            for (HashMap.Entry<String, String> i: cache.entrySet())
                writer.write(i.getValue() +" " +i.getKey() +"\n");
            writer.close();
        }
        catch (IOException e)
        {}
    }

    public boolean HasHash(String path) {
        return cache.containsKey(path);
    }
}
