package com.rv.member.utils;

import android.content.Context;

import com.rv.member.bean.MemberListBean;
import com.rv.member.bean.MemberOrderBean;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/******
 * 会员缓存管理
 */
public class MemberCache {
    private static MemberCache instance = null;

    private Context mContext;

    private MemberCache(Context context) {
        this.mContext = context;
    }

    public static MemberCache getInstance(Context context) {
        if (instance == null) {
            instance = new MemberCache(context);
        }
        return instance;
    }

    /********
     * 保存
     * @param listBean
     */
    public  void save(MemberListBean listBean) {
        if (listBean == null || !listBean.isRel()) {
            return;
        }
        saveObject(listBean);
    }

    private void saveObject(MemberListBean listBean) {
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        File f = new File(getSavePath());
        try {
            fos = new FileOutputStream(f);
            oos = new ObjectOutputStream(fos);
            oos.writeObject(listBean);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (oos != null) {
                    oos.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private String getSavePath() {
        return mContext.getCacheDir().getPath() + File.separator + "member";
    }


    public MemberListBean get() {
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        MemberListBean o = null;
        File f = new File(getSavePath());
        if (!f.exists()) {
            return null;
        }
        try {
            fis = new FileInputStream(f);
            ois = new ObjectInputStream(fis);
            o = (MemberListBean) ois.readObject();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (ois != null) {
                    ois.close();
                }
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return o;
    }
}
