import javax.swing.JOptionPane;
import java.util.Random;
import java.io.BufferedReader;
import java.io.FileReader;

public class KeywordCipher {
    
    public KeywordCipher() throws Exception {
        String keyString = "";
        String alphabet =  "abcdefghijklmnopqrstuvwxyz ";
        char[] alpha = alphabet.toCharArray();
                /*
                permute(alpha);
                for(int i = 0; i < alpha.length; i++ ) {
                        keyString += alpha[i];
                } // end for
                 **/
        keyString = JOptionPane.showInputDialog("Enter Key String","the snow lay thick upon the ground");
        if( keyString == null ) return;
        keyString = keyString.toLowerCase();
        keyString = removeRepeats(keyString);
        for( int i = 0; i < 27; i++ ) {
            if( !keyString.contains(alphabet.charAt(i)+"") ) keyString += alphabet.charAt(i);
        } // end for
        System.out.println("Key = " + keyString+":");
        while( true ) {
            String input = JOptionPane.showInputDialog("Enter Message","meet vaslik at the usual place at ten pm");
            if( input == null ) break;
            input = input.toLowerCase();
            String encrypted = "";
            for( int i = 0; i < input.length(); i++ ) {
                char ch = input.charAt(i);
                if( !Character.isLetter(ch) ) ch = ' ';
                int charInt = keyString.indexOf(ch);
                encrypted += alphabet.charAt(charInt);
            } // end for
            JOptionPane.showMessageDialog(null,"Encrypted message is <" + encrypted + ">");
            String decrypted = "";
            for( int i = 0; i < encrypted.length(); i++ ) {
                int charInt = alphabet.indexOf(encrypted.charAt(i));
                decrypted += keyString.charAt(charInt);
            }// end for
            JOptionPane.showMessageDialog(null,"Decrypted message is <" + decrypted + ">");
        } // end while
    } // end constructor
    
    public static void main(String[] a) throws Exception {
        new KeywordCipher();
    } // end main
    
    public final void permute(char[] chars) {
        Random r = new Random();
        for( int i = 1; i < chars.length; i++ ) {
            char ch = chars[i];
            int j = r.nextInt(i);
            chars[i] = chars[j];
            chars[j] = ch;
        } // end for
    } // end permute
    
    String removeRepeats(String s) {
        String r = "";
        for( int i = 0; i < s.length(); i++ ) {
            if( !r.contains(s.charAt(i)+"") ) r += s.charAt(i);
        } // end for
        return r;
    } // end removeRepeats
    
} // end KeywordCipher
