package cz.fidentis.analyst.core;

import java.awt.BorderLayout;
import java.text.SimpleDateFormat;
import java.time.Duration;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;

/**
 * Wrapper for default output window of the Java Netbeans Platform application.
 * It enables to write debug messages into the window.
 * 
 * @author Radek Oslejsek
 */
public class OutputWindow {

    private static JTextArea textArea; 
    
    private long lastTime = System.currentTimeMillis();
    
    protected OutputWindow() {
        initTextArea();
    }
    
    /**
     * Prints the message.
     * 
     * @param msg Message to be printed
     */
    public static void print(String msg) {
        JTextArea ta = initTextArea();
        ta.setText(ta.getText() 
                + new SimpleDateFormat("HH:mm:ss").format(System.currentTimeMillis())
                + " [duration unknown]: "
                + msg.trim() 
                + System.lineSeparator()
        );
    }

    /**
     * Starts measuring of some operation. 
     * Call {@link #printDuration(java.lang.String)} on returned OutputWindow
     * to print the measured duration.
     * 
     * @return An object used to print measured duration and message
     */
    public static OutputWindow measureTime() {
        OutputWindow ret = new OutputWindow();
        ret.lastTime = System.currentTimeMillis();
        return ret;
    }
    
    /**
     * Prints the message about an operation and the duration of the operation. 
     * The duration is computed as the difference between current system time and 
     * the time of calling {@link #measureTime()}. The time difference is measured in 
     * milliseconds and printed as [+mm:ss.SSS] where mm=minutes, ss=seconds, 
     * and SSS=milliseconds.
     * 
     * @param msg Message to be printed
     */
    public void printDuration(String msg) {
        Duration duration = Duration.ofMillis(System.currentTimeMillis() - lastTime);
        textArea.setText(textArea.getText() 
                + new SimpleDateFormat("HH:mm:ss").format(System.currentTimeMillis())
                + " [duration "
                + String.format(
                        "%02d:%02d.%03d", 
                        duration.toMinutes(), 
                        duration.toSecondsPart(),
                        duration.toMillisPart())
                + "]: "
                + msg.trim() 
                + System.lineSeparator()
        );
    }
    
    protected static JTextArea initTextArea() {
        if (textArea == null) {
            TopComponent outputWin = WindowManager.getDefault().findTopComponent("output");
            textArea = new JTextArea();
            JScrollPane sp = new JScrollPane(textArea);
            outputWin.add(sp, BorderLayout.CENTER);
        }
        return textArea;
    }
}
