package net.knarcraft.serverlauncher.userinterface;

import net.knarcraft.serverlauncher.profile.Profile;

import javax.swing.*;
import javax.swing.text.DefaultCaret;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import static javax.swing.text.DefaultCaret.ALWAYS_UPDATE;

/**
 * Acts as a single writable/readable tab
 * Has a box for user input, and a textArea for server output.
 *
 * @author      Kristian Knarvik <kristian.knarvik@knett.no>
 * @version     0.0.0.1
 * @since       0.0.0.1
 */
public class Console implements ActionListener {
    private final JTextField textInput;
    private final JTextArea textOutput;
    private final String name;
    private final JPanel panel;

    Console(JTabbedPane tab, String name) {
        this.name = name;
        panel = new JPanel();
        tab.addTab(name, null, panel, null);
        panel.setLayout(new BorderLayout(0, 0));
        textInput = new JTextField();
        panel.add(textInput, BorderLayout.SOUTH);
        textInput.setColumns(10);
        textInput.addActionListener(this);
        textOutput = new JTextArea();
        JScrollPane scroll = new JScrollPane(textOutput);
        panel.add(scroll, BorderLayout.CENTER);
        textOutput.setEditable(false);
        DefaultCaret caret = (DefaultCaret) textOutput.getCaret();
        caret.setUpdatePolicy(ALWAYS_UPDATE);
        textOutput.setLineWrap(true);
    }

    public void output(String text) {
        this.textOutput.setText(this.textOutput.getText() + "\n" + text);
    }

    public JPanel getPanel() {
        return this.panel;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == textInput) { //Sends the command from the input to the server with the same name.
            String text = textInput.getText();
            Profile.getCurrent().sendCommand(this.name, text);
            textInput.setText("");
        }
    }
}