import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
import javax.swing.text.Highlighter.HighlightPainter;
import javax.swing.text.BadLocationException;


/**
  *
  * Programm zur Kryptoanalyse
  * von monoalphabetischen Substitutionen
  *
  * @version 1.0 from 23.11.2016
  * @author Thomas Schaller
  */

public class BreakMono extends JFrame {
  // Anfang Attribute
  private JTextField[] buchstabe;
  
  private JButton jButton1 = new JButton();
  private JTable jTable1 = new JTable(10, 2);
  private DefaultTableModel jTable1Model = (DefaultTableModel) jTable1.getModel();
  private JScrollPane jTable1ScrollPane = new JScrollPane(jTable1);
  private JTable jTable2 = new JTable(10, 2);
  private DefaultTableModel jTable2Model = (DefaultTableModel) jTable2.getModel();
  private JScrollPane jTable2ScrollPane = new JScrollPane(jTable2);
  private JTable jTable3 = new JTable(10, 2);
  private DefaultTableModel jTable3Model = (DefaultTableModel) jTable3.getModel();
  private JScrollPane jTable3ScrollPane = new JScrollPane(jTable3);
  private JButton jBBuchstabe = new JButton();
  private JButton jBBigramm = new JButton();
  private JButton jBDoppel = new JButton();
  private String[] h = {"E : 17,4%", "N : 9,8%", "S : 7,9%", "I : 7,6%", "R : 7,0%", "A : 6,5%", "T: 6,2%", "D : 5,1%", "U : 4,4%", "L : 3,5%"};
  private String[] b = {"ER : 4,1%", "EN : 4,0%", "CH : 2,4%", "DE : 2,3%", "EI : 1,9%", "ND : 1,9%", "TE: 1,9%", "IN : 1,7%", "IE : 1,6%", "GE : 1,5%"};
  private String[] t = {"SS : 0,76%", "NN : 0,43%", "LL : 0,42%", "EE : 0,23%", "MM : 0,23%", "TT : 0,23%", "RR: 0,15%", "DD : 0,13%", "FF : 0,12%", "AA : 0,08%"};
    
  private JTextArea jTextArea1 = new JTextArea("");
  private JScrollPane jTextArea1ScrollPane = new JScrollPane(jTextArea1);
  private JTextArea jTextArea2 = new JTextArea("");
  private JScrollPane jTextArea2ScrollPane = new JScrollPane(jTextArea2);
  private JLabel jLabel1 = new JLabel();
  private JLabel jLabel2 = new JLabel();
  private JLabel jLabel4 = new JLabel();
    // Ende Attribute
    
  public BreakMono (String title) {
    super (title);
    setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    int frameWidth = 702; 
    int frameHeight = 651;
    setSize(frameWidth, frameHeight);
    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (d.width - getSize().width) / 2;
    int y = (d.height - getSize().height) / 2;
    setLocation(x, y);
    Container cp = getContentPane();
    cp.setLayout(null);
    // Anfang Komponenten
    jButton1.setBounds(216, 440, 241, 25);
    jButton1.setText("Entschlüsselung versuchen");
    jButton1.setMargin(new Insets(2, 2, 2, 2));
    jButton1.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent evt) { 
        jButton1_ActionPerformed(evt);
      }
    });
    cp.add(jButton1);
    jTable1ScrollPane.setBounds(16, 176, 193, 177);
    jTable1.getColumnModel().getColumn(1).setHeaderValue("Deutsch");
    jTable1.getColumnModel().getColumn(0).setHeaderValue("Dieser Text");
    jTable1.setFont(new Font("@Fixedsys", Font.PLAIN, 12));
    cp.add(jTable1ScrollPane);
    jTable2ScrollPane.setBounds(240, 176, 201, 177);
    jTable2.getColumnModel().getColumn(1).setHeaderValue("Deutsch");
    jTable2.getColumnModel().getColumn(0).setHeaderValue("Dieser Text");
    cp.add(jTable2ScrollPane);
    jTable3ScrollPane.setBounds(480, 176, 193, 177);
    jTable3.getColumnModel().getColumn(1).setHeaderValue("Deutsch");
    jTable3.getColumnModel().getColumn(0).setHeaderValue("Dieser Text");
    cp.add(jTable3ScrollPane);
    jBBuchstabe.setBounds(16, 144, 193, 25);
    jBBuchstabe.setText("Buchstabenhäufigkeit");
    jBBuchstabe.setMargin(new Insets(2, 2, 2, 2));
    jBBuchstabe.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent evt) { 
        jBBuchstabe_ActionPerformed(evt);
      }
    });
    cp.add(jBBuchstabe);
    jBBigramm.setBounds(240, 144, 201, 25);
    jBBigramm.setText("Bigramm-Häufigkeit");
    jBBigramm.setMargin(new Insets(2, 2, 2, 2));
    jBBigramm.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent evt) { 
        jBBigramm_ActionPerformed(evt);
      }
    });
    cp.add(jBBigramm);
    jBDoppel.setBounds(480, 144, 193, 25);
    jBDoppel.setText("Doppelbuchstaben-Häufigkeit");
    jBDoppel.setMargin(new Insets(2, 2, 2, 2));
    jBDoppel.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent evt) { 
        jBDoppel_ActionPerformed(evt);
      }
    });
    cp.add(jBDoppel);
    jTextArea1ScrollPane.setBounds(16, 24, 665, 105);
    JScrollBar jsb = jTextArea1ScrollPane.getVerticalScrollBar();
    jsb.addAdjustmentListener(new AdjustmentListener() {;
      public void adjustmentValueChanged(AdjustmentEvent evt) {
        adjustScrollBars(1);
      }
    });
    jTextArea1.setLineWrap(true);
    jTextArea1.setFont(new Font("Courier New", Font.BOLD, 16));
    jTextArea1.addCaretListener(new CaretListener() {
      
      @Override
        public void caretUpdate(CaretEvent arg0) {
        int dot = arg0.getDot();
        int mark = arg0.getMark();
        updateMarkierung(dot, mark);
      }
    });   
    
    cp.add(jTextArea1ScrollPane);
    jTextArea2ScrollPane.setBounds(16, 480, 665, 105);
    jsb = jTextArea2ScrollPane.getVerticalScrollBar();
    jsb.addAdjustmentListener(new AdjustmentListener() {;
      public void adjustmentValueChanged(AdjustmentEvent evt) {
        adjustScrollBars(2);
      }
    });
    jTextArea2.setLineWrap(true);
    jTextArea2.setFont(new Font("Courier New", Font.BOLD, 16));
    jTextArea2.addCaretListener(new CaretListener() {
      
      @Override
        public void caretUpdate(CaretEvent arg0) {
        int dot = arg0.getDot();
        int mark = arg0.getMark();
        updateMarkierung(dot, mark);
      }
    });   
    
    
    cp.add(jTextArea2ScrollPane);
    jLabel1.setText("Kryptotext");
    jLabel1.setBounds(16, 3, 110, 20);
    cp.add(jLabel1);
    jLabel2.setBounds(16, 456, 110, 20);
    jLabel2.setText("Klartext");
    cp.add(jLabel2);
    jLabel4.setBounds(128, 584, 419, 33);
    jLabel4.setText("(cc) Schaller (ZPG Informatik) - V1.0 (2017)");
    jLabel4.setHorizontalAlignment(SwingConstants.CENTER);
    jLabel4.setFont(new Font("Dialog", Font.PLAIN, 12));
    cp.add(jLabel4);
    // Ende Komponenten
    buchstabe = new JTextField[26];
    for (int i = 0; i<26 ;i++ ) {
      JLabel jLabel3 = new JLabel();
      jLabel3.setBounds(23+i*25, 375, 25, 25);
      int c = 65+i;
      jLabel3.setText(""+((char) c));
      cp.add(jLabel3);
      buchstabe[i] = new JTextField();
      buchstabe[i].setBounds(16+i*25, 400, 25, 25);
      buchstabe[i].setText("");
      buchstabe[i].setHorizontalAlignment(SwingConstants.CENTER);
      buchstabe[i].addKeyListener(new KeyAdapter() {
      public void keyReleased(KeyEvent e) {
      e.consume();
      }
      
      public void keyTyped(KeyEvent e) {
      e.consume();
      }
      
      public void keyPressed(KeyEvent e) {
      JTextField textField = (JTextField) e.getSource();
      String text = textField.getText();
      if ((e.getKeyChar()>='a' && e.getKeyChar()<='z') ||(e.getKeyChar()>='A' && e.getKeyChar()<='Z')) {
      text = ""+e.getKeyChar();
      }
      if (e.getKeyChar()==' ' || e.getKeyChar() == KeyEvent.VK_BACK_SPACE || e.getKeyChar() == KeyEvent.VK_DELETE) {
      text = "";
        
      } // end of if
      textField.setText(text.toUpperCase());
      e.consume();
      jButton1_ActionPerformed(null);
      changeColors();
      
      } // end of if
      
      });
      
      cp.add(buchstabe[i]);    
    } // end of for
    for (int i = 0; i<10 ; i++ ) {
      jTable1.getModel().setValueAt(h[i],i,1);
      jTable2.getModel().setValueAt(b[i],i,1);
      jTable3.getModel().setValueAt(t[i],i,1);
    } // end of for
    
    setResizable(false);
    setVisible(true);
  }
    
    
  public void changeColors() {
    System.out.println("askd");
    for (int i=0; i<26 ; i++ ) {
      buchstabe[i].setBackground(new Color(150,250,150));
      if (buchstabe[i].getText().equals("")) {
        buchstabe[i].setBackground(Color.white);
        
        
        } // end of if
      
    } // end of for
    for (int i= 0; i<26 ;i++ ) {
      for (int j=i+1; j<26  ;j++ ) {
        if (!buchstabe[i].getText().equals("") && buchstabe[i].getText().equals(buchstabe[j].getText())) {
          buchstabe[i].setBackground(new Color(250,150,150));
          buchstabe[j].setBackground(new Color(250,150,150));
        } // end of if
      } // end of for
    } // end of for
  }
    
    
    // Anfang Methoden
  public void jButton1_ActionPerformed(ActionEvent evt) {
    String krypttext = jTextArea1.getText().toLowerCase();
    for (int i=0;i<26 ;i++ ) {
      int c = i+97;
      String z = buchstabe[i].getText().toUpperCase();
      if (z.equals("")) {
        z = "*";
      } // end of if
      if (z.length()>1) {
        buchstabe[i].setText(z.substring(0,1));
      } // end of if
      krypttext = krypttext.replace((char) c,z.charAt(0));
      
    } // end of for
    jTextArea2.setText(krypttext);
  } // end of jButton1_ActionPerformed
    
  public void jBBuchstabe_ActionPerformed(ActionEvent evt) {
    String s = jTextArea1.getText();
    s = s.toLowerCase();
    s = s.replace(" ","");
    ArrayList<Baustein> h = new ArrayList<Baustein>();
    for (int i=0; i < s.length() ; i++ ) {
      String z = s.substring(i,i+1);
      boolean g = false;
      for (Baustein b : h ) {
        if (b.getZeichen().equals(z)) {
          b.incAnzahl();
          g = true;
          break;
          
        } // end of if
      } // end of for
      if (!g) {
        h.add(new Baustein(z));
      }
    } // end of for
    Collections.sort(h);
    for (int i=0; i < 10 && i < h.size() ; i++ ) {
      double x = h.get(i).getAnzahl();
      x = Math.round(x / (double) s.length()*1000.0)/10.0;
      jTable1.getModel().setValueAt(h.get(i).getZeichen()+" : "+x+"%",i,0);
    } // end of for
  } // end of jBBuchstabe_ActionPerformed
    
  public void jBBigramm_ActionPerformed(ActionEvent evt) {
    String s = jTextArea1.getText();
    s = s.toLowerCase();
    int anz=0;
    ArrayList<Baustein> h = new ArrayList<Baustein>();
    for (int i=0; i < s.length()-1 ; i++ ) {
      if (s.charAt(i) != ' ' && s.charAt(i+1) != ' ') {
        anz++;
        String z = s.substring(i,i+2);
        boolean g = false;
        for (Baustein b : h ) {
          if (b.getZeichen().equals(z)) {
            b.incAnzahl();
            g = true;
            break;
            
          } // end of if
        } // end of for
        if (!g) {
          h.add(new Baustein(z));
        }
        
      } // end of if
    } // end of for
    Collections.sort(h);
    for (int i=0; i < 10 && i < h.size() ; i++ ) {
      double x = h.get(i).getAnzahl();
      x = Math.round(x / anz*1000)/10.0;
      jTable2.getModel().setValueAt(h.get(i).getZeichen()+" : "+x+"%",i,0);
    } // end of for
  } // end of jBBigramm_ActionPerformed
    
  public void jBDoppel_ActionPerformed(ActionEvent evt) {
    String s = jTextArea1.getText();
    s = s.toLowerCase();
    int anz = 0;
    ArrayList<Baustein> h = new ArrayList<Baustein>();
    
    for (int i=0; i < s.length()-1 ; i++ ) {
      
      if (s.charAt(i) != ' ' && s.charAt(i+1) != ' ') {
        anz++;
        
        if (s.charAt(i+1) == s.charAt(i) ) {
          String z = s.substring(i,i+2);
          boolean g = false;
          for (Baustein b : h ) {
            if (b.getZeichen().equals(z)) {
              b.incAnzahl();
              g = true;
              break;
              
            } // end of if
          } // end of for
          if (!g) {
            h.add(new Baustein(z));
          }
          
        } // end of if
      }
    } // end of for
    Collections.sort(h);
    for (int i=0; i < 10 && i < h.size() ; i++ ) {
      double x = h.get(i).getAnzahl();
      x = Math.round(x / anz*10000)/100.0;
      jTable3.getModel().setValueAt(h.get(i).getZeichen()+" : "+x+"%",i,0);
    } // end of for
  } // end of jBDoppel_ActionPerformed
    
  public void adjustScrollBars(int i) {
    if (i==1) {
      jTextArea2ScrollPane.getVerticalScrollBar().setValue(jTextArea1ScrollPane.getVerticalScrollBar().getValue());
      
    } else {
      jTextArea1ScrollPane.getVerticalScrollBar().setValue(jTextArea2ScrollPane.getVerticalScrollBar().getValue());
    }
  }
    
  public void updateMarkierung(int p1, int p2) {
    Highlighter h1 = jTextArea2.getHighlighter();
    Highlighter h2 = jTextArea1.getHighlighter();
    h1.removeAllHighlights();
    h2.removeAllHighlights();
    int von = Math.min(p1,p2);
    int bis = Math.max(p1,p2);
    try{
      h1.addHighlight(von ,
      bis,
      new DefaultHighlighter.DefaultHighlightPainter(Color.yellow));
      
    }catch(BadLocationException e) {}
    try{
      h2.addHighlight(von ,
      bis,
      new DefaultHighlighter.DefaultHighlightPainter(Color.yellow));
      
    }catch(BadLocationException e) {}  
      }
      
      
      
    
      
      // Ende Methoden
      
      public static void main(String[] args) {
    new BreakMono("BreakMono");
  }
}
