package hamming.Views;

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

public class HammingVerificationView extends JFrame {
    private JTextField messageRecuField;
    private JTextArea resultArea, logArea;

    public HammingVerificationView() {
        super("Vérification 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 reçu (complet) :"));
        messageRecuField = new JTextField();
        inputPanel.add(messageRecuField);

        JButton verifierButton = new JButton("Vérifier Erreurs");
        inputPanel.add(verifierButton);

        add(inputPanel, BorderLayout.NORTH);

        resultArea = new JTextArea(2, 50);
        resultArea.setEditable(false);
        resultArea.setFont(new Font("SansSerif", Font.BOLD, 14));
        resultArea.setBorder(BorderFactory.createTitledBorder("Diagnostic"));
        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("Calcul du Syndrome"));
        add(new JScrollPane(logArea), BorderLayout.SOUTH);

        verifierButton.addActionListener(e -> verif());
    }

    private void verif() {
        String msg = messageRecuField.getText().trim();
        if(msg.isEmpty()) return;

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

        String res = HammingCalcul.verifierHamming(msg);

        log.stopCapture();
        resultArea.setText(res);
        
        if(res.contains("CORRECT")) resultArea.setBackground(new Color(200, 255, 200));
        else resultArea.setBackground(new Color(255, 200, 200));
    }
}
