package eu.gity.jmeter.serveremulator;

import java.util.regex.Pattern;

import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import org.apache.jmeter.util.JMeterUtils;

import static eu.gity.jmeter.serveremulator.properties.strings.ServerEmulatorPropertiesStrings.SERVER_EMULATOR_ERROR_EMPTY_FIELD;
import static eu.gity.jmeter.serveremulator.properties.strings.ServerEmulatorPropertiesStrings.SERVER_EMULATOR_ERROR_IP;
import static eu.gity.jmeter.serveremulator.properties.strings.ServerEmulatorPropertiesStrings.SERVER_EMULATOR_ERROR_PORT;
import static eu.gity.jmeter.serveremulator.properties.strings.ServerEmulatorPropertiesStrings.SERVER_EMULATOR_INVALID_INPUT;

/**
 * This class takes care of validating user inputs into Server Emulator GUI components.
 *
 * @author Gity a.s.
 */
class ServerEmulatorInputVerifier extends InputVerifier {

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean verify(JComponent input) {
        String name = input.getName();
        String stringValue = ((JTextField) input).getText();

        if (name.equals("ipTFByte") || name.equals("ipTFByte4End")) {
            String textValue = ((JTextField) input).getText();
            if (textValue.equals("")) {
                //Byte4End is an exception because empty field means only one IP shall be used
                if (name.equals("ipTFByte4End")) {
                    return true;
                }
                JOptionPane.showMessageDialog(null, JMeterUtils.getLocaleString(SERVER_EMULATOR_ERROR_EMPTY_FIELD),
                        JMeterUtils.getLocaleString(SERVER_EMULATOR_INVALID_INPUT), JOptionPane.ERROR_MESSAGE);
                return false;
            }

            if (Pattern.matches("^([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])$", stringValue)) {
                return true;
            } else {
                JOptionPane.showMessageDialog(null, JMeterUtils.getLocaleString(SERVER_EMULATOR_ERROR_IP),
                        JMeterUtils.getLocaleString(SERVER_EMULATOR_INVALID_INPUT), JOptionPane.ERROR_MESSAGE);
                return false;
            }
        } else if (name.equals("HTTPPortTF")) {
            if (Pattern.matches("^([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$", stringValue)) {
                return true;
            } else {
                JOptionPane.showMessageDialog(null, JMeterUtils.getLocaleString(SERVER_EMULATOR_ERROR_PORT),
                        JMeterUtils.getLocaleString(SERVER_EMULATOR_INVALID_INPUT), JOptionPane.ERROR_MESSAGE);
                return false;
            }
        } else {
            return false;
        }
    }
}
