package gui;

import db.*;
import hu.elte.inf.pszt.prt.javalib.gui.*;
import hu.elte.inf.pszt.prt.javalib.gui.tablemodel.*;
import hu.elte.inf.pszt.prt.javalib.swingapp.ElteJFrame;
import hu.elte.inf.pszt.prt.javalib.utils.ElteJOptionPane;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;

/**
 * @author trust56 http://lengyel.web.elte.hu/store/prt2/SwingAppBase.zip
 * @contributor Daniel "3ICE" Berezvai
 * @Csoport: B
 */
public class MainFrame extends ElteJFrame {

    protected final String FRAME_TITLE = "Tool Management";
    private DatabaseHandler dbHandler;
    private JTabbedPane tabbedPane;
    private JTable personTable, categoryTable, toolsTable;
    private JpaControlledTableModel<Person> personTableModel;
    private JpaControlledTableModel<Category> categoryTableModel;
    private JpaControlledTableModel<Tool> toolsTableModel;
    private JLabel brokenToolsLabel;

    @Override
    public void onCreate() {
        setDefaults(FRAME_TITLE);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        dbHandler = new DatabaseHandler();
        dbHandler.open();
        tabbedPane = new JTabbedPane();

        personTableModel = new AsyncFullQueryingTableModel<>(
                dbHandler.getPersonJpaController(),
                dbHandler.getEntityClassesToControllersMap());
        personTable = new JTable(personTableModel);
        categoryTableModel = new AsyncFullQueryingTableModel<>(
                dbHandler.getCategoryJpaController(),
                dbHandler.getEntityClassesToControllersMap());
        categoryTable = new JTable(categoryTableModel);
        toolsTableModel = new AsyncFullQueryingTableModel<>(
                dbHandler.getToolJpaController(),
                dbHandler.getEntityClassesToControllersMap());
        toolsTable = new JTable(toolsTableModel);

        // 3ICE: This is bad, should use the new ColumnLabel instead...
        toolsTable.getColumnModel().getColumn(0).setHeaderValue("Name");
        toolsTable.getColumnModel().getColumn(1).setHeaderValue("Assignee");
        toolsTable.getColumnModel().getColumn(2).setHeaderValue("Category");
        toolsTable.getColumnModel().getColumn(3).setHeaderValue("Status");

        tabbedPane.addTab("Tools", new JScrollPane(toolsTable));
        tabbedPane.addTab("(People)", new JScrollPane(personTable));
        tabbedPane.addTab("(Categories)", new JScrollPane(categoryTable));
        getContentPane().add(tabbedPane, BorderLayout.CENTER);

        brokenToolsLabel = new JLabel();
        getContentPane().add(brokenToolsLabel, BorderLayout.NORTH);

//        // 3ICE: MY god, what a hack this would have been...
//        for (int i = 0; i < toolsTable.getRowCount(); i++) {
//            if (toolsTable.getValueAt(i, 3) != "X") {
//                broken_tool_count++;
//            }
//        }

        updateBrokenToolCountDisplay();
    }

    @Override
    public JMenuBar createJMenuBar() {
        JMenuBar menuBar = new JMenuBar();
        JMenu menu = new JMenu("File (Extras)");
        menuBar.add(menu);
        menu.add(new JMenuItem(newPersonAction));
        menu.add(new JMenuItem(newCategoryAction));
        menu.add(new JMenuItem(exitAction));

        menuBar.add(new JMenuItem(newToolAction));
        menuBar.add(new JMenuItem(editToolAction));
        menuBar.add(new JMenuItem(markToolFixedAction));
        menuBar.add(new JMenuItem(exitAction));

        menu.setMnemonic(KeyEvent.VK_F);

        newPersonAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_P);
        newCategoryAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_C);

        newToolAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_N);
        editToolAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_E);
        markToolFixedAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_M);
        exitAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_X);

        return menuBar;
    }
    private Action newToolAction = new AbstractAction("New tool") {
        @Override
        public void actionPerformed(ActionEvent e) {
            Tool t = new Tool();
            EntityEditorDialog<Tool> editorDialog = EntityEditorDialogFactory.
                    createEditorDialog(t, dbHandler.getToolJpaController(),
                    dbHandler.getEntityClassesToControllersMap());
            editorDialog.setVisible(true);
            t.setStatus(true); // 3ICE: Az új eszközök státusza kezdetben mindig karbantartott.
            try {
                dbHandler.getToolJpaController().edit(t);
            } catch (Exception ex) {
                ElteJOptionPane.showError(rootPane,
                        "Unable to create the tool. Error message: "
                        + ex.getMessage());
            }
            toolsTableModel.refresh();
        }
    };
    private Action newPersonAction = new AbstractAction("(New person)") {
        @Override
        public void actionPerformed(ActionEvent e) {
            Person p = new Person();
            EntityEditorDialog<Person> editorDialog = EntityEditorDialogFactory.
                    createEditorDialog(p, dbHandler.getPersonJpaController());
            editorDialog.setVisible(true);
            personTableModel.refresh();
        }
    };
    private Action newCategoryAction = new AbstractAction("(New category)") {
        @Override
        public void actionPerformed(ActionEvent e) {
            Category c = new Category();
            EntityEditorDialog<Category> editorDialog = EntityEditorDialogFactory.
                    createEditorDialog(c, dbHandler.getCategoryJpaController());
            editorDialog.setVisible(true);
            categoryTableModel.refresh();
        }
    };
    private Action editToolAction = new AbstractAction("Edit tool") {
        @Override
        public void actionPerformed(ActionEvent e) {
            int selectedRow = toolsTable.getSelectedRow();
            if (selectedRow == -1) {
                ElteJOptionPane.showError(rootPane,
                        "Please select a tool from the table!");
                return;
            }
            Tool t = dbHandler.getToolJpaController().findEntities().get(
                    selectedRow);
            EntityEditorDialogFactory.createEditorDialog(t,
                    dbHandler.getToolJpaController(),
                    dbHandler.getEntityClassesToControllersMap()).setVisible(true);
            try {
                dbHandler.getToolJpaController().edit(t);
                if (!t.getStatus()) {
                    updateBrokenToolCountDisplay();
                }
            } catch (Exception ex) {
                ElteJOptionPane.showError(rootPane,
                        "Unable to modify the tool. Error message: "
                        + ex.getMessage());
            }
            toolsTableModel.refresh();

        }
    };
    private Action markToolFixedAction = new AbstractAction("Mark tool fixed") {
        @Override
        public void actionPerformed(ActionEvent e) {
            int selectedRow = toolsTable.getSelectedRow();
            if (selectedRow == -1) {
                ElteJOptionPane.showError(rootPane,
                        "Please select a tool from the table!");
            } else {
                Tool t = dbHandler.getToolJpaController().findEntities().get(
                        selectedRow);
                if (t.getStatus()) {
                    ElteJOptionPane.showError(rootPane,
                            "The selected tool is already fixed.");
                    return;
                }
                try {
                    t.setStatus(true);
                    dbHandler.getToolJpaController().edit(t);
                    ElteJOptionPane.showInfo(rootPane,
                            "Marked the tool as fixed!");
                    updateBrokenToolCountDisplay();
                } catch (Exception ex) {
                    ElteJOptionPane.showError(
                            "Cannot mark tool as fixed. Error message: "
                            + ex.getMessage());
                }
                toolsTableModel.refresh();

            }
        }
    };
    private Action exitAction = new AbstractAction("Exit") {
        @Override
        public void actionPerformed(ActionEvent e) {
            dispose();
        }
    };
// /*

    private String getString(String message) {
        return JOptionPane.showInputDialog(rootPane, message, "Data input",
                JOptionPane.QUESTION_MESSAGE);
    }

    private Person getPerson(String message) {
        Object[] ps = dbHandler.getPersonJpaController().findEntities().
                toArray();
        if (ps.length == 0) {
            return null;
        } else {
            return (Person) JOptionPane.
                    showInputDialog(rootPane, message, "Data input",
                    JOptionPane.QUESTION_MESSAGE, null, ps, ps[0]);
        }
    }
// */

    @Override
    public void dispose() {
        dbHandler.close();
        super.dispose();
    }

    private void updateBrokenToolCountDisplay() {
        int broken_tool_count = 0;
        for (Tool tool : dbHandler.getToolJpaController().findEntities()) {
            if (!tool.getStatus()) { // 3ICE: Ha nem true, akkor törött...
                broken_tool_count++;
            }
        }
        brokenToolsLabel.setText(BROKEN_TOOLS_TEXT + broken_tool_count);
    }
    private static final String BROKEN_TOOLS_TEXT = "Broken tools: ";
}
