package org.bdware.sc;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.PrintStream;
import java.util.*;

public class ContractPrinter extends Thread {
    private static final Logger LOGGER = LogManager.getLogger(ContractPrinter.class);
    private Process p;
    private Scanner sc;
    private String TAG;
    private List<PrintStream> psList;
    private Set<PrintStream> toRemove;

    public void track(Process process, Scanner sc, String tag, PrintStream printStream) {
        p = process;
        this.sc = sc;
        this.TAG = tag;
        psList = new ArrayList<>();
        if (null != printStream) {
            psList.add(printStream);
        }
        toRemove = new HashSet<>();
        start();
    }

    public synchronized void redirect(PrintStream ps, String tag) {
        if (null != psList && !psList.contains(ps)) {
            psList.add(ps);
        }
        this.TAG = tag;
    }

    public void run() {
        try {
            while (sc.hasNextLine()) {
                String content = sc.nextLine();
                if (psList.size() == 0) {
                    System.out.println(TAG + content);
                } else {
                    printInList(content);
                }
            }
        } catch (Exception e) {
            LOGGER.warn(e.getMessage());
        }
    }

    private synchronized void printInList(String content) {
        for (PrintStream ps : psList) {
            try {
                ps.println(TAG + content);
            } catch (Exception e) {
                LOGGER.warn(e.getMessage());
                toRemove.add(ps);
            }
        }
        psList.removeAll(toRemove);
        toRemove.clear();
    }

}// Printer