package leigh.eo.json;

import leigh.eo.EO;
import leigh.eo.EOJsonSerializer;
import leigh.eo.io.EOInputStream;
import leigh.mecha.json.JSONObject;
import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.NoSuchElementException;

public class JsonInput implements EOInputStream, AutoCloseable {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(JsonInput.class);
    private final BufferedReader reader;

    public JsonInput(InputStream inputStream) {
        reader = new BufferedReader(new InputStreamReader(inputStream));
    }

    public EO readEo() throws IOException {
        try {
            //  logger.info("==============");
            String line = reader.readLine();
            if (line == null) return null;
            //  logger.info("Line: -->{}<--", line);
            JSONObject jo = new JSONObject(line);
            return EOJsonSerializer.toEo(jo);
        } catch (NoSuchElementException e) {
            return null;
        }
    }

    @Override
    public void close() throws IOException {
        reader.close();
    }
}
