package monnethic.mobile.blockchain.utility;

import android.content.Context;

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

import monnethic.mobile.blockchain.participant.UserContext;

public class Util {

    private Context context;

    public  Util(Context context){
        this.context=context;
    }

    //Method which write user info into a directory
    public  static void writeUserContext(Context context, UserContext userContext){
        ObjectOutputStream out = null;
        FileOutputStream file = null;
        try{
            String filename = userContext.getName()+".context";
            String dirPath = context.getFilesDir()+"userInfos/"+userContext.getAffiliation();
            String pathFile = dirPath+"/"+filename;

            File dir = new File(dirPath);
            if(!dir.exists()){
                dir.mkdirs();
            }

            file = null;
            file = new FileOutputStream(pathFile);
            out = new ObjectOutputStream(file);

            out.writeObject(userContext);
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            try {
                if (out != null){
                    out.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            try{
                if(file != null){
                    file.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    //Method to read user in file
    public static UserContext readUserContext(Context context, String affiliation, String username){
        UserContext userContext = null;
        FileInputStream fileInputStream = null;
        ObjectInputStream in = null;

        try{
            String filename = username+".context";
            String dirPath = context.getFilesDir()+"userInfos/"+affiliation;
            String pathFile = dirPath+"/"+filename;

            File file = new File(pathFile);

            if(file.exists()){
                fileInputStream = new FileInputStream(pathFile);
                in = new ObjectInputStream(fileInputStream);
                userContext = (UserContext) in.readObject();
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            try {
                if(in != null){
                    in.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            try {
                if(fileInputStream!=null){
                    fileInputStream.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return userContext;
    }
}