package tmcsim.client.cadclientgui.screens;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.rmi.RemoteException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import tmcsim.client.cadclientgui.enums.CADDataEnums.TABLE;
import tmcsim.client.cadclientgui.enums.TableHeaders;

/**
 * This class contains the view and controller for the IncidentEditor screen.
 * The view is built using a GUI builder plug-in, and the controller uses
 * listeners to control how the view and data act.
 *
 * @author Stuart
 */
public class IncidentEditor extends javax.swing.JFrame
{
    private final String[] monthNames =
    {
        "January", "February",
        "March", "April", "May", "June", "July", "August", "September",
        "October", "November", "December"
    };
    private final String[] dayNames =
    {
        "Sun", "Mon", "Tue", "Wed",
        "Thu", "Fri", "Sat"
    };
    private DefaultTableModel blankTable;
    private JTable calendarTable;
    private int todayRow;
    private int todayCol;

    /**
     * Creates new form IncidentEditor
     */
    public IncidentEditor()
    {
        declareComponents();
        initControllers();
        initLayout();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed"
    // desc="Generated Code">//GEN-BEGIN:initComponents
    private void declareComponents()
    {

        incidentLogScroll = new javax.swing.JScrollPane();
        incidentLogTable = new javax.swing.JTable();
        agencyTypeLabel = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        agencyTypeList = new javax.swing.JList();
        currentDatabaseLabel = new javax.swing.JLabel();
        currentDatabaseCombo = new javax.swing.JComboBox();
        searchLimitLabel = new javax.swing.JLabel();
        reopenButton = new javax.swing.JButton();
        duplicateCellButton = new javax.swing.JButton();
        searchButton = new javax.swing.JButton();
        printButton = new javax.swing.JButton();
        viewButton = new javax.swing.JButton();
        refreshButton = new javax.swing.JButton();
        exitButton = new javax.swing.JButton();
        fromLabel = new javax.swing.JLabel();
        toLabel = new javax.swing.JLabel();
        fromCalendar = new javax.swing.JPanel();
        toCalendar = new javax.swing.JPanel();
    }

    public MouseListener newMouseListener()
    {
        return new MouseListener()
        {
            public void mouseClicked(MouseEvent e)
            {
                viewButton.setEnabled(true);
            }

            public void mouseEntered(MouseEvent e)
            {
            }

            public void mouseExited(MouseEvent e)
            {
            }

            public void mousePressed(MouseEvent e)
            {
            }

            public void mouseReleased(MouseEvent e)
            {
            }
        };
    }

    public ActionListener newSearchActionListener()
    {
        return new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                ScreenManager.openSearch();
            }
        };
    }

    public ActionListener newViewActionListener()
    {
        return new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                String masterInc = (String) incidentLogTable.getValueAt(
                        incidentLogTable.getSelectedRow(), 5);
                int incidentId = 0;
                try
                {
                    incidentId = ScreenManager.theCoordinator
                            .getIncidentId(masterInc);
                } catch (RemoteException e1)
                {
                    e1.printStackTrace();
                }
                ScreenManager.openIncidentViewer(incidentId);
            }
        };
    }

    public ActionListener newRefreshActionListener()
    {
        return new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                refreshInformation();
            }
        };
    }

    public ActionListener newExitActionListener()
    {
        return new ActionListener()
        {
            public void actionPerformed(ActionEvent arg0)
            {
                close();
            }
        };
    }

    private void initControllers()
    {

        incidentLogTable.addMouseListener(newMouseListener());

        searchButton.addActionListener(newSearchActionListener());
        viewButton.addActionListener(newViewActionListener());
        refreshButton.addActionListener(newRefreshActionListener());
        exitButton.addActionListener(newExitActionListener());
    }

    private void initLayout()
    {
        blankTable = new DefaultTableModel();
        blankTable.setColumnIdentifiers(TableHeaders.INCIDENT_EDITOR_HEADERS);

        setTitle("Incident Editor");
        setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE);
        setPreferredSize(new java.awt.Dimension(800, 600));

        incidentLogTable.setOpaque(true);
        incidentLogTable.setIntercellSpacing(new Dimension(1, 0));
        incidentLogTable.setGridColor(Color.WHITE);
        incidentLogTable.getTableHeader().setReorderingAllowed(false);
        incidentLogTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        incidentLogTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        incidentLogTable.setAutoCreateRowSorter(true);
        incidentLogScroll.setViewportView(incidentLogTable);

        agencyTypeLabel.setText("Agency Type:");

        DefaultListModel<String> dlm = new DefaultListModel();
        dlm.addElement("CHP");
        agencyTypeList.setModel(dlm);
        agencyTypeList.setEnabled(false);

        jScrollPane1.setViewportView(agencyTypeList);

        currentDatabaseLabel.setText("Current Database:");

        currentDatabaseCombo.setModel(new javax.swing.DefaultComboBoxModel(
                new String[]
        {
            "System"
        }));
        currentDatabaseCombo.setEnabled(false);

        searchLimitLabel.setText("Search Limit On Live System: 30 Days");

        fromCalendar = createCalendar();
        toCalendar = createCalendar();

        reopenButton.setText("ReOpen");
        reopenButton.setEnabled(false);

        duplicateCellButton.setText("Duplicate Cell");
        duplicateCellButton.setMargin(new java.awt.Insets(2, 2, 2, 2));
        duplicateCellButton.setEnabled(false);

        searchButton.setText("Search");

        printButton.setText("Print");
        printButton.setEnabled(false);

        viewButton.setText("View");
        viewButton.setEnabled(false);

        refreshButton.setText("Refresh");
        exitButton.setText("Exit");

        fromLabel.setText("From...");

        toLabel.setText("To...");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(incidentLogScroll)
                .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(agencyTypeLabel)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(currentDatabaseLabel)
                .addComponent(currentDatabaseCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addComponent(searchLimitLabel))
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(fromLabel)
                .addComponent(fromCalendar, 200, 200, 200))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 45, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(toLabel)
                .addComponent(toCalendar, 200, 200, 200))
                .addGap(25, 25, 25)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                .addComponent(reopenButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(duplicateCellButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(searchButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(printButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(viewButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(refreshButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(exitButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))));
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                .addComponent(incidentLogScroll, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(agencyTypeLabel)
                .addComponent(reopenButton)
                .addComponent(fromLabel)
                .addComponent(toLabel))
                .addGap(2, 2, 2)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(currentDatabaseLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(currentDatabaseCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(searchLimitLabel))
                .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(fromCalendar, 150, 150, 150)
                .addComponent(toCalendar, 150, 150, 150)))
                .addGroup(layout.createSequentialGroup()
                .addComponent(duplicateCellButton)
                .addGap(2, 2, 2)
                .addComponent(searchButton)
                .addGap(2, 2, 2)
                .addComponent(printButton)
                .addGap(2, 2, 2)
                .addComponent(viewButton)
                .addGap(2, 2, 2)
                .addComponent(refreshButton)
                .addGap(2, 2, 2)
                .addComponent(exitButton)))
                .addGap(0, 41, Short.MAX_VALUE)));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    public JPanel createCalendar()
    {

        JPanel calendarPanel = new JPanel();
        Calendar now = Calendar.getInstance();
        calendarPanel.setBorder(new LineBorder(new Color(0, 0, 0)));
        calendarPanel.setLayout(null);

        JLabel monthLabel = new JLabel("New label");
        monthLabel.setBounds(0, 0, 140, 20);
        monthLabel.setHorizontalAlignment(SwingConstants.CENTER);
        monthLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        monthLabel.setText(monthNames[now.get(Calendar.MONTH)]);
        calendarPanel.add(monthLabel);

        JLabel yearLabel = new JLabel("New label");
        yearLabel.setHorizontalAlignment(SwingConstants.CENTER);
        yearLabel.setBounds(140, 0, 60, 20);
        yearLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        yearLabel.setText(Integer.toString(now.get(Calendar.YEAR)));
        calendarPanel.add(yearLabel);

        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
        String dateString = dateFormat.format(date);

        JLabel dateLabel1 = new JLabel("New label");
        dateLabel1.setBounds(0, 130, 60, 20);
        dateLabel1.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        dateLabel1.setText(dateString);
        dateLabel1.setHorizontalAlignment(JLabel.CENTER);
        calendarPanel.add(dateLabel1);

        JLabel dateLabel2 = new JLabel("New label");
        dateLabel2.setBounds(140, 130, 60, 20);
        dateLabel2.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        dateLabel2.setText(dateString);
        dateLabel2.setHorizontalAlignment(JLabel.CENTER);
        calendarPanel.add(dateLabel2);

        JScrollBar scrollBar = new JScrollBar();
        scrollBar.setOrientation(JScrollBar.HORIZONTAL);
        scrollBar.setBounds(60, 130, 80, 20);
        scrollBar.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        scrollBar.setEnabled(false);
        calendarPanel.add(scrollBar);

        calendarTable = new JTable()
        {
            /*
             * Custom renderer to set different background/foreground colors
             * @see javax.swing.JTable#prepareRenderer(javax.swing.table.TableCellRenderer, int, int)
             */
            public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
            {
                Component comp = super.prepareRenderer(renderer, row, column);
                if (todayRow == row && todayCol == column)
                {
                    comp.setBackground(Color.BLUE);
                    comp.setForeground(Color.WHITE);
                }
                else
                {
                    comp.setBackground(new Color(235, 235, 235));
                    comp.setForeground(Color.BLACK);
                }
                return comp;
            }
        };
        calendarTable.setModel(createDaysModel());
        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment(JLabel.CENTER);
        for (int i = 0; i < dayNames.length; i++)
        {
            calendarTable.getColumnModel().getColumn(i).setCellRenderer(centerRenderer);
        }
        calendarTable.setEnabled(false);
        calendarTable.setBounds(0, 20, 200, 110);
        calendarPanel.add(calendarTable);

        return calendarPanel;
    }

    protected DefaultTableModel createDaysModel()
    {

        String[][] emptyModel =
        {
            {
                "", "", "", "", "", "", ""
            },
            {
                "", "", "", "", "", "", ""
            },
            {
                "", "", "", "", "", "", ""
            },
            {
                "", "", "", "", "", "", ""
            },
            {
                "", "", "", "", "", "", ""
            },
            {
                "", "", "", "", "", "", ""
            },
            {
                "", "", "", "", "", "", ""
            },
            {
                "", "", "", "", "", "", ""
            }
        };

        String[] emptyHeader =
        {
            "", "", "", "", "", "", ""
        };
        DefaultTableModel calendarModel = new DefaultTableModel(emptyModel, emptyHeader);
        int row = 0;
        int col = 0;

        Calendar today = Calendar.getInstance();
        int tMonth = today.get(Calendar.MONTH);
        int tYear = today.get(Calendar.YEAR);
        int tDay = today.get(Calendar.DAY_OF_MONTH);

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MONTH, tMonth);
        calendar.set(Calendar.YEAR, tYear);
        calendar.set(Calendar.DAY_OF_MONTH, 1);

        Calendar iterator = (Calendar) calendar.clone();
        iterator.add(Calendar.DAY_OF_MONTH,
                -(iterator.get(Calendar.DAY_OF_WEEK) - 1));

        Calendar maximum = (Calendar) calendar.clone();
        maximum.add(Calendar.MONTH, +1);

        for (int i = 0; i < dayNames.length; i++)
        {
            calendarModel.setValueAt(dayNames[i], row, col);
            col++;
        }
        col = 0;
        row = 1;

        while (iterator.getTimeInMillis() < maximum.getTimeInMillis())
        {
            int lMonth = iterator.get(Calendar.MONTH);
            int lYear = iterator.get(Calendar.YEAR);

            if ((lMonth == tMonth) && (lYear == tYear))
            {
                int lDay = iterator.get(Calendar.DAY_OF_MONTH);
                calendarModel.setValueAt(Integer.toString(lDay), row, col);
                if ((tMonth == lMonth) && (tYear == lYear) && (tDay == lDay))
                {
                    todayRow = row;
                    todayCol = col;
                }
            }
            iterator.add(Calendar.DAY_OF_YEAR, +1);

            col++;
            if (col >= calendarModel.getColumnCount())
            {
                row++;
                col = 0;
            }
        }


        return calendarModel;
    }

    public void refreshInformation()
    {
        try
        {
            incidentLogTable.setModel(ScreenManager.theCoordinator
                    .getCadDataTable(TABLE.INCIDENT_EDITOR));
        } catch (RemoteException e)
        {
            e.printStackTrace();
        }
    }

    /*
     * Makes screen visible.
     */
    public void open()
    {
        incidentLogTable.setModel(blankTable);
        viewButton.setEnabled(false);
        setVisible(true);
    }

    /*
     * Hides screen.
     */
    public void close()
    {
        setVisible(false);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel agencyTypeLabel;
    private javax.swing.JList agencyTypeList;
    private javax.swing.JComboBox currentDatabaseCombo;
    private javax.swing.JLabel currentDatabaseLabel;
    private javax.swing.JButton duplicateCellButton;
    private javax.swing.JButton exitButton;
    private javax.swing.JPanel fromCalendar;
    private javax.swing.JLabel fromLabel;
    private javax.swing.JScrollPane incidentLogScroll;
    private javax.swing.JTable incidentLogTable;
    private javax.swing.JPanel toCalendar;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton printButton;
    private javax.swing.JButton refreshButton;
    private javax.swing.JButton reopenButton;
    private javax.swing.JButton searchButton;
    private javax.swing.JLabel searchLimitLabel;
    private javax.swing.JLabel toLabel;
    private javax.swing.JButton viewButton;
    // End of variables declaration//GEN-END:variables
}
