package com.easd.tools.iriomote;

/*
 * #%L
 * resttest
 * %%
 * Copyright (C) 2014 EA Systems Dresden GmbH
 * %%
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 * #L%
 */

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.api.client.filter.GZIPContentEncodingFilter;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.MediaType;

/**
 *
 * @author mmauksch
 */
public class GUI extends javax.swing.JFrame {

    private boolean authCBChecked;
    private boolean gzipCBchecked;

    /**
     * Creates new form GUI
     */
    public GUI() {
        authCBChecked = false;
        gzipCBchecked = false;
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        tpMain = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        btTextPost = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        taPostText = new javax.swing.JTextArea();
        jPanel2 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        tpResult = new javax.swing.JTabbedPane();
        jPanel4 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        lbResponse = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        lbSize = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        taPrettyResponse = new javax.swing.JTextArea();
        jPanel5 = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        taRawRequest = new javax.swing.JTextArea();
        jPanel6 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        taResponseRaw = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        tfAddress = new javax.swing.JTextField();
        btGet = new javax.swing.JButton();
        cbAuth = new javax.swing.JCheckBox();
        jLabel3 = new javax.swing.JLabel();
        tfUser = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        tfPassword = new javax.swing.JPasswordField();
        cbGZip = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        tpMain.setName(""); // NOI18N

        btTextPost.setText("Post");
        btTextPost.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btTextPostActionPerformed(evt);
            }
        });

        taPostText.setColumns(20);
        taPostText.setRows(5);
        jScrollPane1.setViewportView(taPostText);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 604, Short.MAX_VALUE)
                    .addComponent(btTextPost, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 340, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btTextPost)
                .addContainerGap())
        );

        tpMain.addTab("Post(Text)", jPanel1);

        jLabel2.setText("Not implemented yet");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(234, 234, 234)
                .addComponent(jLabel2)
                .addContainerGap(246, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(84, 84, 84)
                .addComponent(jLabel2)
                .addContainerGap(296, Short.MAX_VALUE))
        );

        tpMain.addTab("Post(Binary)", jPanel2);

        jLabel5.setText("Response: ");

        lbResponse.setText("none");

        jLabel6.setText("Size: ");

        lbSize.setText("none");

        taPrettyResponse.setEditable(false);
        taPrettyResponse.setColumns(20);
        taPrettyResponse.setRows(5);
        jScrollPane2.setViewportView(taPrettyResponse);

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 599, Short.MAX_VALUE)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lbResponse)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lbSize)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(lbResponse)
                    .addComponent(jLabel6)
                    .addComponent(lbSize))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 323, Short.MAX_VALUE)
                .addContainerGap())
        );

        tpResult.addTab("Pretty", jPanel4);

        taRawRequest.setEditable(false);
        taRawRequest.setColumns(20);
        taRawRequest.setRows(5);
        taRawRequest.setText("not implemented yet");
        jScrollPane4.setViewportView(taRawRequest);

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 599, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 344, Short.MAX_VALUE)
                .addContainerGap())
        );

        tpResult.addTab("Raw (Request)", jPanel5);

        taResponseRaw.setEditable(false);
        taResponseRaw.setColumns(20);
        taResponseRaw.setRows(5);
        jScrollPane3.setViewportView(taResponseRaw);

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 599, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 344, Short.MAX_VALUE)
                .addContainerGap())
        );

        tpResult.addTab("Raw (Response)", jPanel6);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(tpResult, javax.swing.GroupLayout.Alignment.TRAILING)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(tpResult)
        );

        tpMain.addTab("Result", jPanel3);

        jLabel1.setText("Address: ");

        tfAddress.setText("http://rest.example.org");

        btGet.setText("Get");
        btGet.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btGetActionPerformed(evt);
            }
        });

        cbAuth.setText("HTTPAuth?");
        cbAuth.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbAuthItemStateChanged(evt);
            }
        });

        jLabel3.setText("Name: ");

        tfUser.setText("User");

        jLabel4.setText("Password: ");

        tfPassword.setText("Password");

        cbGZip.setText("GZip?");
        cbGZip.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbGZipItemStateChanged(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tpMain)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tfAddress, javax.swing.GroupLayout.PREFERRED_SIZE, 475, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btGet))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(cbAuth)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tfUser, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tfPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cbGZip)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(tfAddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btGet))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cbAuth)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4)
                    .addComponent(tfUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cbGZip))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tpMain)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private Builder configureBuilder() {
        Client clientToUse;
        //Creates a client that doesn't check the validity of ssl certifcates. 
        //Should only be used in a trusted environment!
         clientToUse = Client.create(ClientHelper.configureClient());
        //Create standard client:
         //clientToUse = Client.create();
        if(authCBChecked) {
            clientToUse.addFilter(new HTTPBasicAuthFilter(tfUser.getText(), tfPassword.getText()));
        }
        if(gzipCBchecked) {
            clientToUse.addFilter(new GZIPContentEncodingFilter(true));
        }
        WebResource web = clientToUse.resource(tfAddress.getText());
        WebResource.Builder builder = web.type(MediaType.APPLICATION_JSON);
        //builder.accept(MediaType.APPLICATION_JSON);
        return builder;
    }
    
    private void handleClientResponse(ClientResponse response) {
        StringBuilder rawBuilder = new StringBuilder();
        lbResponse.setText(Integer.toString(response.getStatus()));
        lbSize.setText(Integer.toString(response.getLength()));
        for(Map.Entry<String, List<String>> entry : response.getHeaders().entrySet()) {
            rawBuilder.append(entry.getKey());
            rawBuilder.append(": ");
            for(int i = 0; i < entry.getValue().size(); i++) {
                rawBuilder.append(entry.getValue().get(i));
                rawBuilder.append((i==entry.getValue().size()-1)?";\n":", ");
            }
        }
        String entity = response.getEntity(String.class);
        rawBuilder.append(entity);
        taResponseRaw.setText(rawBuilder.toString());
        taPrettyResponse.setText(entity);
        tpMain.setSelectedIndex(2);
        tpResult.setSelectedIndex(0);
    }

    private void btTextPostActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btTextPostActionPerformed
        Builder builder = configureBuilder();
        handleClientResponse(builder.post(ClientResponse.class, taPostText.getText()));
        
    }//GEN-LAST:event_btTextPostActionPerformed

    private void btGetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btGetActionPerformed
        Builder builder = configureBuilder();
        handleClientResponse(builder.get(ClientResponse.class));
    }//GEN-LAST:event_btGetActionPerformed

    private void cbAuthItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbAuthItemStateChanged
        if(evt.getSource() == cbAuth) {
            authCBChecked = !authCBChecked;
        }
    }//GEN-LAST:event_cbAuthItemStateChanged

    private void cbGZipItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbGZipItemStateChanged
        if(evt.getSource() == cbGZip) {
            gzipCBchecked = !gzipCBchecked;
        }
    }//GEN-LAST:event_cbGZipItemStateChanged

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btGet;
    private javax.swing.JButton btTextPost;
    private javax.swing.JCheckBox cbAuth;
    private javax.swing.JCheckBox cbGZip;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JLabel lbResponse;
    private javax.swing.JLabel lbSize;
    private javax.swing.JTextArea taPostText;
    private javax.swing.JTextArea taPrettyResponse;
    private javax.swing.JTextArea taRawRequest;
    private javax.swing.JTextArea taResponseRaw;
    private javax.swing.JTextField tfAddress;
    private javax.swing.JPasswordField tfPassword;
    private javax.swing.JTextField tfUser;
    private javax.swing.JTabbedPane tpMain;
    private javax.swing.JTabbedPane tpResult;
    // End of variables declaration//GEN-END:variables
}
