package strings;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import main.*;
import javax.swing.*;
/**
* A class that encodes or decodes an entered String or .txt-File to a selected code.
* @author Mario Trageser
*
*/
public class StringEncoder
{
static JFrame f;
/**
* Encodes or decodes an entered String or .txt-File with an selected encoding- or decoding-method.
* @throws FileNotFoundException
*/
public StringEncoder() throws FileNotFoundException
{
String s = "";
String product = "";
String encode = "Enter the string you want to encode";
String decode = "Enter the string you want to decode";
String[] encodingMethods = {"Morse Code", "Caesar Code"};
String[] encodeDecodeOptions = {"encode", "decode"};
String[][] morseCodeAlphabet = {{".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."}, {"-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----."}};
int encodingMethod = Utils.selectTool(f, "Select the encoding- or decoding-method you want to use.", "select encoding/decoding method", encodingMethods);
int encodeDecode = Utils.selectTool(f, "Do you want to encode or decode the string", "encode or decode", encodeDecodeOptions);
switch(encodingMethod)
{
case 0:
switch(encodeDecode)
{
case 0:
s = Utils.enterFileOrString(f, encode).toUpperCase();
for(int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
if(c >= 'A' && c <= 'Z')
{
product += morseCodeAlphabet[0][c - 'A'] + " ";
}
if(c >= '0' && c <= '9')
{
product += morseCodeAlphabet[1][c - '0'] + " ";
}
}
break;
case 1:
s = Utils.enterFileOrString(f, decode).toUpperCase() + " ";
List<MatchResult> results = new ArrayList<MatchResult>();
Matcher m = Pattern.compile(".*? ").matcher(s);
while(m.find())
{
results.add(m.toMatchResult());
}
for(MatchResult r : results)
{
String codePart = r.group().trim();
for(int i = 0; i < morseCodeAlphabet[0].length; i++)
{
if(codePart.equals(morseCodeAlphabet[0][i]))
{
product += (char) ('A' + i);
}
}
for(int i = 0; i < morseCodeAlphabet[1].length; i++)
{
if(codePart.equals(morseCodeAlphabet[1][i]))
{
product += (char) ('0' + i);
}
}
}
}
break;
case 1:
}
JOptionPane.showMessageDialog(f, product, "Morse Code", 1);
}
}