/**
 * 
 */
package cz.neubauer.tomas.hazardanalysis.viewcontroller.dangeranalysis;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

import cz.neubauer.tomas.hazardanalysis.model.dangers.DangerVariant;
import cz.neubauer.tomas.hazardanalysis.model.stages.Stage;
import cz.neubauer.tomas.hazardanalysis.model.stages.StageManager;
import cz.neubauer.tomas.hazardanalysis.model.stages.VariantStage;
import cz.neubauer.tomas.hazardanalysis.viewcontroller.MainFrame;

/**
 * @author Tomáš Neubauer
 */
public class CriticalDangerAnalysisFrame extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8160786472107551281L;

	private MainFrame owner;

	private JTabbedPane tpnZalozky;

	private JPanel pnlButtons;

	private JButton btnForms, btnExport;

	private StagePanel spnVyroba, spnPrepravaMontazInstalace,
			spnUvedeniDoProvozu, spnPouzivani, spnVyrazeniZProvozu;

	private ArrayList<DangerVariant> criticalVariants;

	private StageManager stageManager;

	private DangerEstimationFrame dangerEstimationFrame;

	public CriticalDangerAnalysisFrame(MainFrame owner,
			ArrayList<DangerVariant> criticalVariants) {
		this.owner = owner;
		this.criticalVariants = criticalVariants;
		Collections.sort(this.criticalVariants);

		stageManager = new StageManager();
		stageManager.loadFromDB(owner.getApplication().getConnection());

		initGUI();
		setVisible(true);
	}

	/**
	 * 
	 */
	private void initGUI() {
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		setTitle("Analýza významných nebezpečí");

		initTabbedPanel();
		this.add(tpnZalozky, BorderLayout.CENTER);

		initButtonsPanel();
		this.add(pnlButtons, BorderLayout.SOUTH);

		pack();
	}

	/**
	 * 
	 */
	private void initTabbedPanel() {
		tpnZalozky = new JTabbedPane();

		spnVyroba = new StagePanel(this, stageManager.getStage(0),
				criticalVariants);
		tpnZalozky.addTab("Výroba", spnVyroba);

		spnPrepravaMontazInstalace = new StagePanel(this, stageManager
				.getStage(1), criticalVariants);
		tpnZalozky.addTab("Přeprava, montáž a instalace",
				spnPrepravaMontazInstalace);

		spnUvedeniDoProvozu = new StagePanel(this, stageManager.getStage(2),
				criticalVariants);
		tpnZalozky.addTab("Uvedení do provozu", spnUvedeniDoProvozu);

		spnPouzivani = new StagePanel(this, stageManager.getStage(3),
				criticalVariants);
		tpnZalozky.addTab("Používání", spnPouzivani);

		spnVyrazeniZProvozu = new StagePanel(this, stageManager.getStage(4),
				criticalVariants);
		tpnZalozky.addTab("Vyřazení z provozu", spnVyrazeniZProvozu);

	}

	/**
	 * 
	 */
	private void initButtonsPanel() {
		pnlButtons = new JPanel(new FlowLayout(FlowLayout.CENTER));

		btnForms = new JButton("Formuláře pro odhad rizika");
		btnForms.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				btnFormsPerformed();
			}
		});
		pnlButtons.add(btnForms);

		btnExport = new JButton("export");
		btnExport.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				btnExportPerformed();
			}
		});
		pnlButtons.add(btnExport);
	}

	/**
	 * 
	 */
	protected void btnExportPerformed() {
		spnPouzivani.exportData(4, "etapa-pouzivani.txt");
		spnPrepravaMontazInstalace.exportData(2,
				"etapa-preprava-montaz-instalace.txt");
		spnUvedeniDoProvozu.exportData(3, "etapa-uvedeni-do-provozu.txt");
		spnVyrazeniZProvozu.exportData(5, "etapa-vyrazeni-z-provozu.txt");
		spnVyroba.exportData(1, "etapa-vyroba.txt");

		exportCriticalDangers("prehled-zavaznych-nebezpeci.txt",
				"seznam-zavaznych-nebezpeci.txt");
		if (dangerEstimationFrame != null) {
			dangerEstimationFrame.export("odhad");
		}
	}

	/**
	 * @param string
	 */
	private void exportCriticalDangers(String viewFile,
			String criticalDangersListFile) {
		BufferedWriter bw = null;
		BufferedWriter bw2 = null;
		Statement stmt = null;

		HashMap<Integer, Integer> counts = new HashMap<Integer, Integer>(10);
		try {
			String conditions = " where ";
			int dt_id = 0;
			for (int i = 0; i < criticalVariants.size(); i++) {
				dt_id = criticalVariants.get(i).getDangerType().getId();
				if (counts.get(dt_id) == null) {
					counts.put(dt_id, 1);
				} else {
					counts.put(dt_id, counts.get(dt_id) + 1);
				}
				if (i > 0) {
					conditions += " or ";
				}
				conditions += "dv.id=" + criticalVariants.get(i).getId();
			}

			stmt = owner.getApplication().getConnection().createStatement();
			stmt
					.executeQuery("select dg.id as dg_id, dg.name as dg_name, dt.id as dt_id, dt.code as dt_code,"
							+ " dt.description as dt_description,"
							+ " dt.column_cast2_a1_1995 as dt_column_cast2_a1_1995,"
							+ " dt.column_cast1_r1991 as dt_column_cast1_R1991,"
							+ " dt.column_cast2_r1991 as dt_column_cast2_R1991,"
							+ " dt.column_csn_en_iso_12100_1_2003 as dt_column_csn_en_iso_12100_1_2003,"
							+ " dt.column_csn_en_iso_12100_2_2003 as dt_column_csn_en_iso_12100_2_2003,"
							+ " dt.column_normy_typu_b as dt_column_normy_typu_b,"
							+ " dt.column_clanky_csn_en_12415_2001 as dt_column_clanky_csn_en_12415_2001,"
							+ " dt.situation_description as dt_situation_description, dv.description as dv_description from ((danger_variant dv) join (danger_type dt) on (dv.danger_type_id = dt.id)) join (danger_group dg) on (dt.danger_group_id = dg.id)"
							+ conditions + " order by dv.id asc");
			ResultSet rs = stmt.getResultSet();
			bw = new BufferedWriter(new FileWriter(new File(viewFile)));
			bw2 = new BufferedWriter(new FileWriter(new File(
					criticalDangersListFile)));
			int oldDGID = 0, newDGID;
			int oldDTID = 0, newDTID;
			int i = 1;
			while (rs.next()) {
				// přehled identifikovanych záv. nebezp.
				newDGID = rs.getInt("dg_id");
				if (newDGID != oldDGID) {
					bw.write(rs.getInt("dg_id") + " " + rs.getString("dg_name")
							+ "\n");
					oldDGID = newDGID;
				}

				newDTID = rs.getInt("dt_id");
				if (newDTID != oldDTID) {
					bw.write("\t" + rs.getString("dt_code") + " "
							+ rs.getString("dt_description") + "\n");

					// seznam záv. nebezp.
					bw2.write(rs.getString("dt_code") + ";");
					bw2.write(rs.getString("dt_description") + ";");
					bw2.write(rs.getString("dt_column_cast2_a1_1995") + ";");
					bw2.write(rs.getString("dt_column_cast1_R1991") + ";");
					bw2.write(rs.getString("dt_column_cast2_R1991") + ";");
					bw2.write(rs.getString("dt_column_csn_en_iso_12100_1_2003")
							+ ";");
					bw2.write(rs.getString("dt_column_csn_en_iso_12100_2_2003")
							+ ";");
					bw2.write(rs.getString("dt_situation_description") + ";");
					bw2.write(rs.getString("dt_column_normy_typu_b") + ";");
					bw2.write(rs
							.getString("dt_column_clanky_csn_en_12415_2001")
							+ ";");
					Integer count = null;
					if ((count = counts.get(newDTID)) == null) {
						count = new Integer(0);
					}
					bw2.write(String.valueOf(count));
					bw2.newLine();

					oldDTID = newDTID;
					i = 1;
				}

				bw.write("\t\t" + rs.getString("dt_code") + "-" + (i++) + " "
						+ rs.getString("dv_description") + "\n");

			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (stmt != null) {
				try {
					stmt.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}

			if (bw != null) {
				try {
					bw.close();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					if (bw2 != null) {
						try {
							bw2.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}

		}
	}

	/**
	 * 
	 */
	protected void btnFormsPerformed() {
		if (criticalVariants.size() > 0) {
			ArrayList<VariantStage> data = new ArrayList<VariantStage>(3);
			for (int i = 0; i < 5; i++) {
				Stage s = stageManager.getStage(i);
				ArrayList<DangerVariant> variants = s.getDangerVariants();
				for (int j = 0; j < variants.size(); j++) {
					data.add(new VariantStage(variants.get(j), j, s));
				}
			}

			if (data.size() > 0) {
				if (dangerEstimationFrame == null) {
					dangerEstimationFrame = new DangerEstimationFrame(owner
							.getApplication(), this, data);
				} else {
					dangerEstimationFrame.setVariantStagesData(data);
					dangerEstimationFrame.setVisible(true);
				}
			}
		} else {
			JOptionPane.showMessageDialog(this,
					"Není stanoveno žádné závažné nebezpečí!", "Chyba!",
					JOptionPane.ERROR_MESSAGE);
		}

	}

	public void refresh() {
		spnVyroba.refresh();
		spnPrepravaMontazInstalace.refresh();
		spnUvedeniDoProvozu.refresh();
		spnVyrazeniZProvozu.refresh();
		spnPouzivani.refresh();
	}

	public ArrayList<DangerVariant> getCriticalVarians() {
		return criticalVariants;
	}
}
