package hamming.Views;

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.*;
import hamming.Controllers.LogCapture;
import hamming.Models.HammingCalcul;

public class HammingGenerationView extends JFrame {
    private JTextField messageField;
    private JTextArea resultArea, logArea;

    public HammingGenerationView() {
        super("Génération Hamming");
        init();
        setSize(600, 500);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setVisible(true);
    }

    private void init() {
        setLayout(new BorderLayout());

        JPanel inputPanel = new JPanel(new GridLayout(2, 2, 5, 5));
        inputPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        inputPanel.add(new JLabel("Message binaire (ex: 1011) :"));
        messageField = new JTextField();
        inputPanel.add(messageField);

        JButton genererButton = new JButton("Calculer Hamming");
        inputPanel.add(genererButton);

        add(inputPanel, BorderLayout.NORTH);

        resultArea = new JTextArea(2, 50);
        resultArea.setEditable(false);
        resultArea.setFont(new Font("SansSerif", Font.BOLD, 14));
        resultArea.setBorder(BorderFactory.createTitledBorder("Résultat (Mot complet)"));
        add(new JScrollPane(resultArea), BorderLayout.CENTER);

        logArea = new JTextArea(15, 50);
        logArea.setEditable(false);
        logArea.setFont(new Font("Monospaced", Font.PLAIN, 12));
        logArea.setBorder(BorderFactory.createTitledBorder("Étapes du calcul"));
        add(new JScrollPane(logArea), BorderLayout.SOUTH);

        genererButton.addActionListener(e -> calcul());
    }

    private void calcul() {
        String msg = messageField.getText().trim();
        if(!msg.matches("[01]+")) {
            resultArea.setText("Erreur : Entrez seulement des 0 et 1");
            return;
        }

        logArea.setText("");
        LogCapture log = new LogCapture(logArea);
        log.startCapture();

        String res = HammingCalcul.genererHamming(msg);

        log.stopCapture();
        resultArea.setText(res);
    }
}
