package geisplugin.popup.actions;


import geisplugin.Activator;
import geisplugin.Tools;

import java.math.BigInteger;
import java.sql.SQLException;

import javax.swing.JOptionPane;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;

/**
 * DE:
 *
 * EN:
 *
 *
 * Program changes
 * **************************************************************************************
 * Date			* Ticket	* KonzFirm	* Responsible	* programmer    *
 * Change										*
 * **************************************************************************************
 *
 * @author huellmante
 * @version 1.0
 *
 */


public class ChecksumSingleFigure extends AbstractHandler {

	@Override
	public Object execute(final ExecutionEvent event) throws ExecutionException {
		try {
			if (Tools.isNotUpToDate()) {
				return null;
			} 
		} finally {
			try {
				if (Tools.con != null && !Tools.con.isClosed()) {
					try {
						Tools.con.rollback();
						Tools.con.close();
					} catch (final SQLException e) {
					}
					Tools.con = null;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		String originalValue = JOptionPane.showInputDialog(Activator.frame, "Calculate single figure checksum of:");
		if (originalValue != null && !originalValue.trim().isEmpty()) {
			originalValue = originalValue.trim();
			JOptionPane.showMessageDialog(Activator.frame, Integer.toString(berechnePZ1(originalValue)));
		}
		return null;
	}

	private static int berechnePZ1(final String wert) {
		int mp = 3;
		int pz = 0;
		BigInteger bi = null;
		for (int pos = wert.length() - 1; pos >= 0; pos--) {
			bi = new BigInteger(wert.substring(pos, pos + 1));
			pz = pz + (bi.intValue() * mp);
			mp = (mp == 3) ? 1 : 3;
		}
		pz = 10 - (pz % 10);
		if (pz == 10) {
			pz = 0;
		}
		return pz;
	}
}
