package org.bdware.sc.commParser.BDLedger;

import org.bdware.sc.util.HashUtil;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.util.ArrayList;
import java.util.List;

public class BlockBody {
    public List<Transaction> trans = new ArrayList<>();

    public static BlockBody fromBytes(byte[] input) {
        try {
            DataInputStream bin = new DataInputStream(new ByteArrayInputStream(input));
            int size = bin.readInt();
            size = HashUtil.toLittleEndian(size);
            BlockBody ret = new BlockBody();
            for (int i = 0; i < size; i++) {
                Transaction trans = new Transaction();
                ret.trans.add(trans);
                trans.srcID = new byte[20];
                trans.dstID = new byte[20];
                bin.read(trans.srcID);
                bin.read(trans.dstID);
                trans.nonce = HashUtil.toLittleEndian(bin.readLong());
                trans.type = HashUtil.toLittleEndian(bin.readInt());
                int len = HashUtil.toLittleEndian(bin.readInt());
                trans.data = new byte[len];
                bin.read(trans.data);
            }
            return ret;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new BlockBody();
    }

    public byte[] toByteArray() {
        byte[] arr = new byte[1];
        try {
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            DataOutputStream bin = new DataOutputStream(bo);
            bin.writeInt(trans.size());
            for (int i = 0; i < trans.size(); i++) {
                Transaction tran = trans.get(i);
                bin.write(tran.srcID);
                bin.write(tran.dstID);
                bin.writeLong(tran.nonce);
                bin.writeInt(tran.type);
                int len = tran.data.length;
                bin.writeInt(len);
                bin.write(tran.data);
            }
            return bo.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return arr;
    }
}
