package geisplugin.popup.actions;


import geisplugin.Activator;
import geisplugin.Tools;

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 ChecksumLFS 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 originalLFSNumber = JOptionPane.showInputDialog(Activator.frame, "Calculate LFS checksum of:");
		if (originalLFSNumber != null && originalLFSNumber.trim().length() == 9) {
			originalLFSNumber = originalLFSNumber.trim();
			JOptionPane.showMessageDialog(Activator.frame, Integer.toString(getCreateLFSPruefziffer(originalLFSNumber)));
		} else {
			JOptionPane.showMessageDialog(Activator.frame, "The number has to be 9 digits long!");
		}
		return null;
		
	}
	
	private static int getCreateLFSPruefziffer(final String originalLFSNumber) {
		/*
		 * Berechnung der 1-stelligen Prüfziffer für
		 *
		 * 1=Behälteretiketten
		 * 2=LE-Etiketten
		 * 3=Packstücketiketten
		 * 4=Lagerplatz
		 *
		 */

		int zahlInt = 0;
		String zahlString = null;
		int summeInt = 0;
		int tmpSummeInt = 0;
		int gewichtung = 1;

		try {
			if (originalLFSNumber.length() == 9) {
				for (int i = 0; i < originalLFSNumber.length(); ++i) {
					if (gewichtung == 3) {
						gewichtung = 1;
					} else if (gewichtung == 1) {
						gewichtung = 3;
					}
					zahlString = originalLFSNumber.substring(i, i + 1);
					zahlInt = Integer.parseInt(zahlString);
					tmpSummeInt = gewichtung * zahlInt;
					summeInt = summeInt + tmpSummeInt;
				}
				summeInt = 10 - (summeInt % 10);
			}
		} catch (final Exception e) {
			e.printStackTrace();
		}
		return (summeInt == 10) ? 0 : summeInt;
	}
}
