/*
 *  Name:    $Id: OperationPanel.java,v 1.7 2010/02/05 12:52:51 t724w Exp $
 * 
 *  Copyright 2009 Bundesamt für Informatik und Telekommunikation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package ch.admin.bit.edec.evv.ui.swing;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import ch.admin.bit.edec.dsig.Environment;
import ch.admin.bit.edec.dsig.ValidationResult;
import ch.admin.bit.edec.dsig.out.ByteArrayOutputter;
import ch.admin.bit.edec.evv.ui.EVVValidator;

/**
 * 
 * @author mru
 * 
 */
public class OperationPanel extends JPanel implements FileInputChangedListener {

	private final static int TEXT_LENGTH = 20;

	private String inputFile;
	private String inputCRL;
	private String inputCA;

	private JTextArea textArea;
	private JTextField status;
	private JLabel statusIcon;

	private JFileChooser fileChooser;

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public OperationPanel(MainApp mainApp) {

		fileChooser = new JFileChooser();

		JLabel label = new JLabel("Status:");

		status = new JTextField(TEXT_LENGTH);

		label.setLabelFor(status);

		status.setEditable(false);
		// status.setOpaque(true);
		status.setBackground(Color.WHITE);

		// FileNameExtensionFilter filter = new FileNameExtensionFilter(
		// "Text files", "txt", "log");
		//
		// fileChooser.setFileFilter(filter);

		setLayout(new GridLayout(0, 1));

		textArea = new JTextArea();

		JScrollPane scrollPane = new JScrollPane(textArea);
		textArea.setEditable(false);
		textArea.addMouseListener(new EditPopupMenuMouseListener());

		add(scrollPane);

		JPanel buttons = new JPanel();

		buttons.setLayout(new FlowLayout(FlowLayout.LEFT));
		buttons.add(createValidateButton());
		buttons.add(createSaveButton());

		buttons.add(label);
		buttons.add(status);

		ImageIcon icon = Environment.createImageIcon("/info.png");

		if (icon != null) {
			statusIcon = new JLabel(icon);
			buttons.add(statusIcon);
		}

		mainApp.add(buttons, BorderLayout.SOUTH);
	}

	public void onFilePathChanged(String path, FileInputType source) {

		switch (source) {
		case CA:
			inputCA = path;
			break;

		case CRL:
			inputCRL = path;
			break;

		case EVV:
			inputFile = path;
			break;

		default:
			break;
		}

	}

	private JButton createSaveButton() {

		JButton button = new JButton();
		button.setText("save log");

		button.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				showSaveDialog();
			}
		});

		return button;
	}

	private JButton createValidateButton() {
		JButton button = new JButton();
		button.setText("validate");

		button.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				validateEVV();
			}
		});

		return button;
	}

	private void validateEVV() {
		EVVValidator evvValidator = new EVVValidator();

		ByteArrayOutputStream bas = new ByteArrayOutputStream();

		ByteArrayOutputter buffer = new ByteArrayOutputter(bas);

		evvValidator.addOutputterStrategy(buffer);

		ValidationResult result = evvValidator.validateFromFile(inputFile,
				inputCA, inputCRL, null, null, false);

		if (result.isValid()) {
			status.setBackground(Color.GREEN);
			status.setText("OK!");
			ImageIcon icon = Environment.createImageIcon("/valid.png");

			if (icon != null) {
				statusIcon.setIcon(icon);
			}

		} else {
			status.setBackground(Color.RED);
			status.setText("NOT OK!");

			ImageIcon icon = Environment.createImageIcon("/error.png");

			if (icon != null) {
				statusIcon.setIcon(icon);
			}
		}

		textArea.setText(bas.toString());

		try {
			bas.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void showSaveDialog() {

		int returnVal = fileChooser.showSaveDialog(this);

		if (returnVal == JFileChooser.APPROVE_OPTION) {
			File file = fileChooser.getSelectedFile();

			String text = textArea.getText();

			try {
				FileOutputStream fos = new FileOutputStream(file);

				fos.write(text.getBytes());
				fos.close();

			} catch (Exception e) {

				e.printStackTrace();

				JOptionPane.showMessageDialog(fileChooser, e.getMessage(),
						"Error", JOptionPane.ERROR_MESSAGE);

			}

		}

	}
}
