package com.aluxoft.earrecognition.utils;

import android.app.Application;
import android.content.Context;
import android.os.Environment;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.channels.FileChannel;

/**
 * Created by josejuliomartinez on 25/11/15.
 */
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;

        private 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;
        }
    }




}
