/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cryptolearning;

//import com.sun.codemodel.JOp;
import com.sun.rave.web.ui.appbase.AbstractFragmentBean;
import com.sun.webui.jsf.component.ImageComponent;
import com.sun.webui.jsf.component.StaticText;
import core.ExMath;
import javax.faces.FacesException;
import javax.faces.component.html.HtmlCommandButton;
import javax.faces.component.html.HtmlInputText;
import javax.swing.JOptionPane;

/**
 * <p>Fragment bean that corresponds to a similarly named JSP page
 * fragment.  This class contains component definitions (and initialization
 * code) for all components that you have defined on this fragment, as well as
 * lifecycle methods and event handlers where you may add behavior
 * to respond to incoming events.</p>
 *
 * @version ElGalmanSifrovani.java
 * @version Created on 28.3.2009, 11:44:31
 * @author jirka
 */

public class ElGalmanSifrovani extends AbstractFragmentBean {
    // <editor-fold defaultstate="collapsed" desc="Managed Component Definition">

    /**
     * <p>Automatically managed component initialization. <strong>WARNING:</strong>
     * This method is automatically generated, so any user-specified code inserted
     * here is subject to being replaced.</p>
     */
    private void _init() throws Exception {
    }
    private HtmlInputText txtMessage = new HtmlInputText();

    public HtmlInputText getTxtMessage() {
        return txtMessage;
    }

    public void setTxtMessage(HtmlInputText hit) {
        this.txtMessage = hit;
    }
    // </editor-fold>

    public String Message;
    private StaticText labCharNo = new StaticText();

    public StaticText getLabCharNo() {
        return labCharNo;
    }

    public void setLabCharNo(StaticText st) {
        this.labCharNo = st;
    }
    private HtmlCommandButton btnNext1 = new HtmlCommandButton();

    public HtmlCommandButton getBtnNext1() {
        return btnNext1;
    }

    public void setBtnNext1(HtmlCommandButton hcb) {
        this.btnNext1 = hcb;
    }
    private StaticText labA = new StaticText();

    public StaticText getLabA() {
        return labA;
    }

    public void setLabA(StaticText st) {
        this.labA = st;
    }
    private StaticText labCurrChar = new StaticText();

    public StaticText getLabCurrChar() {
        return labCurrChar;
    }

    public void setLabCurrChar(StaticText st) {
        this.labCurrChar = st;
    }
    private StaticText labMessage = new StaticText();

    public StaticText getLabMessage() {
        return labMessage;
    }

    public void setLabMessage(StaticText st) {
        this.labMessage = st;
    }
    private HtmlCommandButton btnNext2 = new HtmlCommandButton();

    public HtmlCommandButton getBtnNext2() {
        return btnNext2;
    }

    public void setBtnNext2(HtmlCommandButton hcb) {
        this.btnNext2 = hcb;
    }
    private StaticText labPrenos = new StaticText();

    public StaticText getLabPrenos() {
        return labPrenos;
    }

    public void setLabPrenos(StaticText st) {
        this.labPrenos = st;
    }
    private ImageComponent imgArrowBigRight1 = new ImageComponent();

    public ImageComponent getImgArrowBigRight1() {
        return imgArrowBigRight1;
    }

    public void setImgArrowBigRight1(ImageComponent ic) {
        this.imgArrowBigRight1 = ic;
    }
    private StaticText labASCII = new StaticText();

    public StaticText getLabASCII() {
        return labASCII;
    }

    public void setLabASCII(StaticText st) {
        this.labASCII = st;
    }
    private HtmlInputText txtX = new HtmlInputText();

    public HtmlInputText getTxtX() {
        return txtX;
    }

    public void setTxtX(HtmlInputText hit) {
        this.txtX = hit;
    }
    private HtmlInputText txtKlic = new HtmlInputText();

    public HtmlInputText getTxtKlic() {
        return txtKlic;
    }

    public void setTxtKlic(HtmlInputText hit) {
        this.txtKlic = hit;
    }
    private StaticText labGama = new StaticText();

    public StaticText getLabGama() {
        return labGama;
    }

    public void setLabGama(StaticText st) {
        this.labGama = st;
    }
    private StaticText labDelta = new StaticText();

    public StaticText getLabDelta() {
        return labDelta;
    }

    public void setLabDelta(StaticText st) {
        this.labDelta = st;
    }
    private HtmlInputText txtGama = new HtmlInputText();

    public HtmlInputText getTxtGama() {
        return txtGama;
    }

    public void setTxtGama(HtmlInputText hit) {
        this.txtGama = hit;
    }
    private HtmlInputText txtDelta = new HtmlInputText();

    public HtmlInputText getTxtDelta() {
        return txtDelta;
    }

    public void setTxtDelta(HtmlInputText hit) {
        this.txtDelta = hit;
    }

    public ElGalmanSifrovani() {

    }

    /**
     * <p>Callback method that is called whenever a page containing
     * this page fragment is navigated to, either directly via a URL,
     * or indirectly via page navigation.  Override this method to acquire
     * resources that will be needed for event handlers and lifecycle methods.</p>
     * 
     * <p>The default implementation does nothing.</p>
     */
    @Override
    public void init() {
        // Perform initializations inherited from our superclass
        super.init();
        // Perform application initialization that must complete
        // *before* managed components are initialized
        // TODO - add your own initialiation code here
        
        
        // <editor-fold defaultstate="collapsed" desc="Visual-Web-managed Component Initialization">
        // Initialize automatically managed components
        // *Note* - this logic should NOT be modified
        try {
            _init();
        } catch (Exception e) {
            log("Page1 Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e: new FacesException(e);
        }
        
        // </editor-fold>
        // Perform application initialization that must complete
        // *after* managed components are initialized
        // TODO - add your own initialization code here
    }

    /**
     * <p>Callback method that is called after rendering is completed for
     * this request, if <code>init()</code> was called.  Override this
     * method to release resources acquired in the <code>init()</code>
     * resources that will be needed for event handlers and lifecycle methods.</p>
     * 
     * <p>The default implementation does nothing.</p>
     */
    @Override
    public void destroy() {
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected SessionBean1 getSessionBean1() {
        return (SessionBean1) getBean("SessionBean1");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected ApplicationBean1 getApplicationBean1() {
        return (ApplicationBean1) getBean("ApplicationBean1");
    }

    public String button1_action() {
        Message = txtMessage.getValue().toString();
        String ASCII = "";

        for (int i=0; i<Message.length(); i++)
        {
            char c = Message.charAt(i);
            Integer charCode = (int) c;
            ASCII += " " + charCode.toString();
        }

        labCharNo.setText("1");
        btnNext1.setDisabled(false);
        labASCII.setText(ASCII);
                
        int[] arr = CheckPublicKey(txtKlic.getValue().toString());

        if (arr==null || arr[0]<255 || !ExMath.isPrime(arr[0]))
            JOptionPane.showMessageDialog(null, "Chybný formát klíče.");
        else
        {
            txtKlic.setDisabled(true);
            btnNext1.setDisabled(false);
            txtMessage.setDisabled(true);
        }

        

        return null;
    }

    private int[] CheckPublicKey(String klic)
    {
        // kontrola klice
        String cislo = "";
        int iCount = 0;
        int[] arr = new int[3];

        for (int i=0; i<klic.length(); i++)
        {
            char c = klic.charAt(i);

            if (c<'0' || c>'9') {
               if (cislo.length()>0)
                arr[iCount++] = Integer.parseInt(cislo) ;
               cislo = "";
            }
            else 
            {
                cislo+=c;
                if ( i==klic.length()-1)
                {
                     if (cislo.length()>0)
                    arr[iCount++] = Integer.parseInt(cislo) ;
                }
            }
        }

        if (iCount!=3) return null;
        else return arr;
    }

    public String btnNext1_action() {
       try
       {
           String message = txtMessage.getValue().toString();
            Integer charNo = Integer.parseInt(labCharNo.getText().toString());
            Integer x = Integer.parseInt(txtX.getValue().toString());
            int[] arr = CheckPublicKey(txtKlic.getValue().toString());
            int n = arr[0];
            int b = arr[1];
            int Y = arr[2];
            char c = message.charAt(charNo-1);

            if ( x<1 || x>n-2)
            {
                JOptionPane.showMessageDialog(null, "Zadané x má chybný formát.");
                return null;
            }

            if ((n-1) % x == 0)
            {
                JOptionPane.showMessageDialog(null, "X musí být nesoudělné s n-1");
                return null;
            }

           Integer gama = ExMath.Exp(b, x) % n;
           Integer delta = (c*ExMath.Exp(Y, x))%n;

           charNo++;

           labGama.setText(gama.toString());
           labDelta.setText(delta.toString());
           
           labCharNo.setText(charNo.toString());
           imgArrowBigRight1.setVisible(true);
           labPrenos.setVisible(true);
           txtGama.setValue(gama);
           txtDelta.setValue(delta);
           btnNext1.setDisabled(true);
           btnNext2.setDisabled(false);
           
       }
       catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Zadané x musí být číslo.");
        }

        return null;
    }

    public String btnNext2_action() {
        try
        {
            Integer gama = Integer.parseInt(txtGama.getValue().toString());
            Integer delta = Integer.parseInt(txtDelta.getValue().toString());
            String msg;
            try {
               msg = labMessage.getText().toString();
            }
            catch (Exception e)
            {
                msg = "";
            }


            int[] arr = CheckPublicKey(txtKlic.getValue().toString());
            int n = arr[0];
            int b = arr[1];
            int Y = arr[2];

            int A = ExMath.Exp(gama, n-1-Y) % n;
            char c = (char) ((A*delta)%n);

            labCurrChar.setText(c);
            msg += c;
            labMessage.setText(msg);
            labA.setText(A);

            btnNext1.setDisabled(false);
            btnNext2.setDisabled(true);
        }
        catch (Exception e)
        {
            JOptionPane.showMessageDialog(null, "Chybně zadané gama nebo delta.");
        }
        return null;
    }

}
