package fanch.multijeu.common.core;

import android.app.Activity;
import android.content.Context;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;

public class DataLoader {

    public static interface ISaveable extends Serializable{
        boolean save(OutputStream stream);
        boolean save(Activity c, String key);
        SerializedObject saveToSerializedObject();
        byte[] saveToByteArray();
    }



    protected static ISaveable load(InputStream fis)
    {
        ObjectInputStream is = null;
        try {
            is = new ObjectInputStream(fis);
            ISaveable obj = (ISaveable) is.readObject();
            is.close();
            return obj;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static ISaveable load(Activity s, String key)
    {
        File f  = s.getFilesDir();
        try {
            FileInputStream fis = s.openFileInput(key);
            ISaveable obj = load(fis);
            fis.close();
            return obj;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static ISaveable load(SerializedObject obj)
    {
        ByteArrayInputStream bv = new ByteArrayInputStream(obj.getBytes());
        ISaveable s = load(bv);
        try {
            bv.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s;
    }

}
