/*
 * Copyright Avaya Inc., All Rights Reserved.
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF Avaya Inc.
 *
 * The copyright notice above does not evidence any actual or intended
 * publication of such source code.
 *
 * Some third-party source code components may have been modified from their
 * original versions by Avaya Inc.
 *
 * The modifications are Copyright Avaya Inc., All Rights Reserved.
 */

package com.avaya.oceanalytics.openinterface.websocketclient;

import com.avaya.oceanalytics.openinterface.websocketclient.websocket.SuppressibleRealtimeDataHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.atomic.AtomicBoolean;

@Component()
public class ConsoleMessagePrinter implements SuppressibleRealtimeDataHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(ConsoleMessagePrinter.class);

    private final AtomicBoolean isQuiet;
    private final OutputStream outputStream;
    private final ObjectMapper mapper;

    @Autowired
    public ConsoleMessagePrinter(ObjectMapper mapper) {
        this.isQuiet = new AtomicBoolean(false);
        this.outputStream = System.out; //NOSONAR
        this.mapper = mapper;
    }

    @Override
    public void handle(String message) {
        LOGGER.info(message);

        if (!isQuiet.get()) {
            try {
                Object json = mapper.readValue(message, Object.class);
                String prettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json)
                        + System.lineSeparator();
                outputStream.write(prettyJson.getBytes());
            } catch (IOException e) {
                LOGGER.error("Unable to output realtime data", e);
            }
        }
    }

    @Override
    public void suppress(boolean quiet) {
        this.isQuiet.set(quiet);
    }

    @Override
    public boolean isSuppressed() {
        return isQuiet.get();
    }

}
