/*
 Copyright by Boston University, 2016
 Authors: Josejulio Martínez, Daniel Kornhauser
 Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
 */
package com.aluxoft.earrecognition.utils;

import android.content.Context;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

public class FileCache extends File {

    private static final long invalidationThreshold;

    static {
        // One hour.
        invalidationThreshold = 1000 * 60 * 60;
    }


    public enum FileCacheType {
        Image("Auriclon_image_file.jpg"),
        Features("Auriclon_features_file.json");

        private String filename;

        FileCacheType(String filename) {
            this.filename = filename;
        }
    }

    private FileCache(File dir, String name) {
        super(dir, name);
    }

    public static FileCache getFile(Context context, FileCacheType type) {
        File dir = context.getCacheDir();
        return new FileCache(dir, type.filename);
    }

    public boolean isValid() {
        return (System.currentTimeMillis() - this.lastModified()) < FileCache.invalidationThreshold;
    }

    public boolean replaceContent(String content) {
        try {
            this.delete();
            this.createNewFile();
            FileUtils.writeStringToFile(this, content);
        } catch (IOException e) {
            return false;
        }
        return true;
    }

    public boolean replaceContent(File imageFile) {
        try {
            this.delete();
            this.createNewFile();
            FileUtils.copyFile(imageFile, this, false);
            return true;
        } catch(IOException exception) {
            return false;
        }
    }

}
