package org.bdware.analysis.dynamic;

import com.google.gson.JsonObject;
import org.bdware.sc.util.JsonUtil;

import java.io.InputStream;
import java.util.*;

public class TracedFile {
    public List<Transaction> trans;

    public TracedFile(InputStream in) {
        Scanner sc = new Scanner(in);
        trans = new ArrayList<>();
        Transaction transaction = new Transaction();
        transaction.tmToVal = new HashMap<>();
        // TODO ignore handle transaction start
        // TODO ignore handle contractID/method....
        // TODO ignore handle transaction end
        while (sc.hasNextLine()) {
            JsonObject jo = JsonUtil.parseStringAsJsonObject(sc.nextLine());
            if (null != jo.get("traceMark")) {
                if (null != jo.get("lval")) {
                    transaction.insert(jo.get("traceMark").getAsInt(), jo.get("lval").getAsInt());
                    transaction.insert(jo.get("traceMark").getAsInt(), jo.get("rval").getAsInt());
                } else {
                    transaction.insert(jo.get("traceMark").getAsInt(), jo.get("val").getAsInt());
                }
            }
        }
        trans.add(transaction);
        sc.close();
    }

    public static class Transaction {
        public Map<Integer, List<Integer>> tmToVal;

        public void insert(int traceMark, int val) {
            List<Integer> ret;
            if (!tmToVal.containsKey(traceMark)) {
                ret = new ArrayList<>();
                tmToVal.put(traceMark, ret);
            } else {
                ret = tmToVal.get(traceMark);
            }
            ret.add(val);
        }
    }
}
