/*
 * Created by JFormDesigner on Thu Jan 04 15:01:53 CST 2024
 */

package tech.nevets.dlite;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.plaf.BorderUIResource;

import net.miginfocom.swing.*;
import tech.nevets.dlite.components.SmartScroller;

/**
 * @author steven
 */
public class ChatWindow extends JPanel {
    private static ChatWindow instance;

    private boolean connected = false;
    private boolean darkModeBool = true;

    public ChatWindow() {
        initComponents();
        instance = this;
    }

    public static ChatWindow getInstance() {
        return instance;
    }

    public void resetConnection(boolean error) {
        connected = false;
        connStatus.setText(error ? "Disconnected: Socket Reset" : "Disconnected");
        connectBtn.setText("Connect");
    }

    private void connectBtnMouseClicked(MouseEvent e) {
        if (connected) {
            ConnectionManager.closeActiveConnection();
            connStatus.setText("Disconnected");
            connectBtn.setText("Connect");
            connected = false;
        } else {
            Connection conn;
            try {
                conn = new Connection(username.getText(), connAddr.getText());
                ConnectionManager.setActiveConnection(conn);
            } catch (final Exception ex) {
                connStatus.setText("Error: " + ex.getMessage());
                connAddr.setBorder(new BorderUIResource(BorderFactory.createLineBorder(Color.RED)));
                return;
            }
            chat.setText("");
            conn.setComponents(chat, onlineUsers);
            connStatus.setText("Connected");
            connectBtn.setText("Disconnect");
            connected = true;
        }
    }

    private void connAddrKeyPressed(KeyEvent e) {
        connAddr.setBorder(UIManager.getBorder("TextField.border"));
    }

    private void usernameFocusGained(FocusEvent e) {
        if (username.getText().trim().equals("Username")) {
            username.setText("");
        }
    }

    private void usernameFocusLost(FocusEvent e) {
        if (username.getText().trim().isEmpty()) {
            username.setText("Username");
        }
    }

    private void connAddrFocusGained(FocusEvent e) {
        if (connAddr.getText().trim().equals("Address:Port")) {
            connAddr.setText("");
        }
    }

    private void connAddrFocusLost(FocusEvent e) {
        if (connAddr.getText().trim().isEmpty()) {
            connAddr.setText("Address:Port");
        }
    }

    private void sendBtnMouseClicked(MouseEvent e) {
        Connection conn = ConnectionManager.getActiveConnection();
        if (conn == null) {
            return;
        }
        conn.sendMessage(messageBox.getText().trim());
        messageBox.setText("");
    }

    private void messageBoxKeyPressed(KeyEvent e) {
        if (e.getKeyCode() == 10 && !messageBox.getText().trim().isEmpty()) {
            sendBtnMouseClicked(null);
        }
    }

    private void darkModeMouseClicked(MouseEvent e) {
        if (darkModeBool) {
            Main.setDarkMode(false);
            darkModeBool = false;
            darkMode.setText("Dark Mode");
        } else {
            Main.setDarkMode(true);
            darkModeBool = true;
            darkMode.setText("Light Mode");
        }
    }

    private void usernameKeyTyped(KeyEvent e) {
        if (username.getText().length() > 15) {
            e.consume();
        }
    }

    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents  @formatter:off
        connStatus = new JLabel();
        darkMode = new JButton();
        username = new JTextField();
        connAddr = new JTextField();
        connectBtn = new JButton();
        chatScrollPane = new JScrollPane();
        chat = new JTextArea();
        new SmartScroller(chatScrollPane, SmartScroller.VERTICAL, SmartScroller.END);
        onlineScrollPane = new JScrollPane();
        onlineUsers = new JTextArea();
        messageBox = new JTextField();
        sendBtn = new JButton();

        //======== this ========
        setPreferredSize(new Dimension(720, 480));
        setLayout(new MigLayout(
            "fill,hidemode 3",
            // columns
            "[161,fill]" +
            "[298,grow,fill]" +
            "[94,shrink 0,center]",
            // rows
            "0[24,top]0" +
            "[24,shrink 0,center]" +
            "[grow]" +
            "[24]"));

        //---- connStatus ----
        connStatus.setText("Disconnected");
        add(connStatus, "cell 0 0 2 1,aligny center,growy 0");

        //---- darkMode ----
        darkMode.setText("Light Mode");
        darkMode.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                darkModeMouseClicked(e);
            }
        });
        add(darkMode, "cell 2 0,growx");

        //---- username ----
        username.setText("Username");
        username.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                usernameFocusGained(e);
            }
            @Override
            public void focusLost(FocusEvent e) {
                usernameFocusLost(e);
            }
        });
        username.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                usernameKeyTyped(e);
            }
        });
        add(username, "cell 0 1,growy");

        //---- connAddr ----
        connAddr.setText("Address:Port");
        connAddr.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                connAddrKeyPressed(e);
            }
        });
        connAddr.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                connAddrFocusGained(e);
            }
            @Override
            public void focusLost(FocusEvent e) {
                connAddrFocusLost(e);
            }
        });
        add(connAddr, "cell 1 1,growy");

        //---- connectBtn ----
        connectBtn.setText("Connect");
        connectBtn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        connectBtn.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                connectBtnMouseClicked(e);
            }
        });
        add(connectBtn, "cell 2 1,grow");

        //======== chatScrollPane ========
        {
            chatScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
            chatScrollPane.setAutoscrolls(true);

            //---- chat ----
            chat.setEditable(false);
            chat.setFont(new Font("Tahoma", Font.PLAIN, 11));
            chat.setLineWrap(true);
            chatScrollPane.setViewportView(chat);
        }
        add(chatScrollPane, "cell 0 2 2 1,grow");

        //======== onlineScrollPane ========
        {
            onlineScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
            onlineScrollPane.setAutoscrolls(true);

            //---- onlineUsers ----
            onlineUsers.setEditable(false);
            onlineScrollPane.setViewportView(onlineUsers);
        }
        add(onlineScrollPane, "cell 2 2,grow");

        //---- messageBox ----
        messageBox.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                messageBoxKeyPressed(e);
            }
        });
        add(messageBox, "cell 0 3 2 1,growy");

        //---- sendBtn ----
        sendBtn.setText("Send");
        sendBtn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        sendBtn.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                sendBtnMouseClicked(e);
            }
        });
        add(sendBtn, "cell 2 3,grow");
        // JFormDesigner - End of component initialization  //GEN-END:initComponents  @formatter:on
    }

    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables  @formatter:off
    private JLabel connStatus;
    private JButton darkMode;
    private JTextField username;
    private JTextField connAddr;
    private JButton connectBtn;
    private JScrollPane chatScrollPane;
    private JTextArea chat;
    private JScrollPane onlineScrollPane;
    private JTextArea onlineUsers;
    private JTextField messageBox;
    private JButton sendBtn;
    // JFormDesigner - End of variables declaration  //GEN-END:variables  @formatter:on
}
