package fanch.multijeu.common.core;

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

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

public class Saveable implements DataLoader.ISaveable {

    public boolean save(OutputStream stream)
    {
        try {
            ObjectOutputStream os = new ObjectOutputStream(stream);
            os.writeObject(this);
            os.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean save(Activity c, String key)
    {
        boolean d;
        File f  = c.getFilesDir();
        try {
            FileOutputStream fos = c.openFileOutput(key, Context.MODE_PRIVATE);
            d=save(fos);
            fos.close();
            return d;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public SerializedObject saveToSerializedObject() {
        return new SerializedObject(saveToByteArray());
    }

    public byte[] saveToByteArray()
    {
        ByteArrayOutputStream bv = new ByteArrayOutputStream();
        //BytesOutpuStream bv = new BytesOutpuStream();
        save(bv);
        try {
            bv.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bv.toByteArray();
    }

}