package auction;

import java.io.*;
import javax.naming.*;
import javax.ejb.*;
import java.rmi.RemoteException;
import java.util.*;
import java.text.NumberFormat;
import bidder.*;
import registration.*;
import seller.*;
import search.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.awt.*;
import java.text.*;
import javax.swing.table.*;
import javax.swing.tree.*;


public class AuctionClient implements ActionListener{ 

//Change the standalone value to false if you want to
//run this program with your ejb server
    final static boolean standaloneMode=true;
    javax.naming.Context ctx=null;

    JMenuBar mb = new JMenuBar();
    JMenu file = new JMenu("File");
    JMenu reports = new JMenu("Reports");
    JMenuItem filePrint = new JMenuItem("Print");
    JSeparator separator = new JSeparator();
    JMenuItem fileQuit = new JMenuItem("Quit");
    JMenuItem itemList = new JMenuItem("List All Items");
    JMenuItem browseItems = new JMenuItem("Browse Items");
    JFrame frame=new JFrame();
    JViewport innerPort, headers;
    JScrollBar scrollBar;
    JScrollPane scrollPane;
    JTable fixedTable, scrollTable;
    TableColumnModel fixedColumnModel, scrollColumnModel;
    int rowHeight=64;
    JTree tree;
    DefaultMutableTreeNode[] nodes;
    JTextField findField;
    JPanel homePanel=null;
    JPanel browsePanel=null;
    JPanel scrollPanel=null;

    public AuctionClient() {

       if(!standaloneMode) {
        try {
           ctx = getInitialContext();
        } catch (Exception e) {
           System.out.println("error contacting EJB server"+e);
        }
      }

        /* Add menu items to menus */
       file.add(filePrint);
       file.add(separator);
       file.add(fileQuit);
       reports.add(itemList);
       reports.add(browseItems);
       mb.add(file);
       mb.add(reports);
       frame.setJMenuBar(mb);

       filePrint.addActionListener(this);
       fileQuit.addActionListener(this);
       itemList.addActionListener(this);
       browseItems.addActionListener(this);
       homePanel = new JPanel();
       homePanel.setLayout(new CardLayout());
       browsePanel = new JPanel();
       browsePanel.setLayout(new BorderLayout());
       scrollPanel = new JPanel();
       scrollPanel.setLayout(new BorderLayout());
       homePanel.add(scrollPanel, "List All Items");
       homePanel.add(browsePanel, "Browse Items");
       frame.getContentPane().add(homePanel, BorderLayout.CENTER);

       frame.setSize(200,100);
       frame.setVisible(true);
    }

    public void actionPerformed(ActionEvent evt) {
        Object obj = evt.getSource();

        if (obj == itemList) {
           try {
               listAllItems();
               ((CardLayout)homePanel.getLayout()).show(homePanel, 
		((JMenuItem)obj).getText());
           } catch (Exception e) {
              System.out.println("Exception: "+e);
           }
        } else if (obj == browseItems) {
           try {
               browseItems();
               ((CardLayout)homePanel.getLayout()).show(homePanel, 
		((JMenuItem)obj).getText());
           } catch (Exception e) {
              System.out.println("Exception: "+e);
           }
     
        } else if (obj == fileQuit) {
           frame.dispose();
           System.exit(0);
        }
    }

    static public javax.naming.Context getInitialContext() 
		throws Exception {
        Properties p = new Properties();
        p.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY,
          "weblogic.jndi.TengahInitialContextFactory");
        return new InitialContext(p);
    }

    private void listAllItems() throws IOException {

        ResultsModel rm=new ResultsModel();
        if(!standaloneMode) {
           try {
               BidderHome bhome=(BidderHome) ctx.lookup("bidder");
               Bidder bid=bhome.create();
               Enumeration enum=(Enumeration)bid.getItemList();
               if(enum != null) {
                  rm.update(enum);
               }
            } catch (Exception e) {
              System.out.println("AuctionServlet <list>:"+e);
            }
        } else {
        
           TestData td= new TestData();
           rm.update(td.results());
        }

        scrollTable=new JTable(rm);
        adjustColumnWidth(scrollTable.getColumn("End Date"), 150);
        scrollTable.setRowHeight(rowHeight);
        adjustColumnWidth(scrollTable.getColumn("Description"), 120);
        scrollColumnModel = scrollTable.getColumnModel();
        fixedColumnModel = new DefaultTableColumnModel();   

        TableColumn col = scrollColumnModel.getColumn(0);
        scrollColumnModel.removeColumn(col);
        fixedColumnModel.addColumn(col);           

        fixedTable = new JTable(rm,fixedColumnModel);    
        fixedTable.setRowHeight(scrollTable.getRowHeight());

        headers = new JViewport();

        ListSelectionModel fixedSelection = fixedTable.getSelectionModel(); 
        fixedSelection.addListSelectionListener(new ListSelectionListener() { 
            public void valueChanged(ListSelectionEvent e) { 
               ListSelectionModel lsm = (ListSelectionModel)e.getSource(); 
               if (!lsm.isSelectionEmpty())  { 
                  setScrollableRow();
               } 
            } 
        }); 

        ListSelectionModel scrollSelection = scrollTable.getSelectionModel(); 
        scrollSelection.addListSelectionListener(new ListSelectionListener() { 
            public void valueChanged(ListSelectionEvent e) { 
               ListSelectionModel lsm = (ListSelectionModel)e.getSource(); 
               if (!lsm.isSelectionEmpty())  { 
                  setFixedRow();
               } 
            } 
        }); 

        CustomRenderer custom = new CustomRenderer();
        custom.setHorizontalAlignment(JLabel.CENTER);
        scrollColumnModel.getColumn(2).setCellRenderer(custom);             
        scrollColumnModel.getColumn(3).setCellRenderer(new CustomButtonRenderer());             
        CustomButtonEditor customEdit=new CustomButtonEditor(frame);
        scrollColumnModel.getColumn(3).setCellEditor(customEdit);             

        headers.add(scrollTable.getTableHeader());          

        JPanel topPanel = new JPanel();
        topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.X_AXIS));
        adjustColumnWidth(fixedColumnModel.getColumn(0), 100);

        JTableHeader fixedHeader=fixedTable.getTableHeader();
        fixedHeader.setAlignmentY(Component.TOP_ALIGNMENT);
        topPanel.add(fixedHeader);
        topPanel.add(Box.createRigidArea(new Dimension(2, 0)));
        topPanel.setPreferredSize(new Dimension(400, 40));

        JPanel headerPanel = new JPanel();
        headerPanel.setAlignmentY(Component.TOP_ALIGNMENT);
        headerPanel.setLayout(new BorderLayout());      

        JScrollPane scrollpane = new JScrollPane();
        scrollBar = scrollpane.getHorizontalScrollBar();

        headerPanel.add(headers, "North");            
        headerPanel.add(scrollBar, "South");
        topPanel.add(headerPanel);           
        scrollTable.setPreferredScrollableViewportSize( new 
		Dimension(300,rowHeight*scrollTable.getRowCount()));
        fixedTable.setPreferredScrollableViewportSize( new 
		Dimension(100,rowHeight*fixedTable.getRowCount()));
        fixedTable.setPreferredSize( new 
		Dimension(100,rowHeight*fixedTable.getRowCount())); 

        innerPort = new JViewport();
        innerPort.setView(scrollTable);
        scrollpane.setViewport(innerPort);        

        scrollBar.getModel().addChangeListener(new ChangeListener()  {
               public void stateChanged(ChangeEvent e)
                      {
                       Point q = headers.getViewPosition();
                       Point p = innerPort.getViewPosition();
                       int val = scrollBar.getModel().getValue();
                       p.x = val;
                       q.x = val;
                       headers.setViewPosition(p);
                       headers.repaint(headers.getViewRect());
                       innerPort.setViewPosition(p);
                       innerPort.repaint(innerPort.getViewRect());
                      }
              });                                                  
        

        scrollTable.getTableHeader().setUpdateTableInRealTime(false); 
        
        JPanel bottomPanel = new JPanel();
        bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.X_AXIS));
        fixedTable.setAlignmentY(Component.TOP_ALIGNMENT);
        bottomPanel.add(fixedTable);
        bottomPanel.add(Box.createRigidArea(new Dimension(2, 0)));
        innerPort.setAlignmentY(Component.TOP_ALIGNMENT);
        bottomPanel.add(innerPort);
        bottomPanel.add(Box.createRigidArea(new Dimension(2, 0)));

        scrollPane= new JScrollPane(bottomPanel,
                     JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                     JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);        
        JViewport outerPort = new JViewport();       
        outerPort.add(bottomPanel);       
        scrollPane.setColumnHeaderView(topPanel);     
        scrollPane.setViewport(outerPort);           

        //scrollpane.getViewport().putClientProperty
         //              ("EnableWindowBlit", Boolean.TRUE);

        scrollTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        scrollPanel.add(scrollPane);
    
        scrollTable.validate();
        frame.setSize(450,200);
    }

    void setFixedRow() {
       int index=scrollTable.getSelectedRow();
       fixedTable.setRowSelectionInterval(index, index);
    }

    void setScrollableRow() {
       int index=fixedTable.getSelectedRow();
       scrollTable.setRowSelectionInterval(index, index);
    }

    void adjustColumnWidth(TableColumn c, int size) {
        c.setPreferredWidth(size);
        c.setMaxWidth(size);
        c.setMinWidth(size);
    }

    private void browseItems() throws IOException {      
       JPanel findPanel;
       JButton findButton;
       Vector newItems=new Vector();
       Vector closedItems=new Vector();
       Bidder bid=null;
       Enumeration enum;
 
       String[] treelabels = { "All Auctions", "Closed Auction", 
		"New Auctions"};
       try {
          if (!standaloneMode) {
               BidderHome bhome=(BidderHome) ctx.lookup("bidder");
               bid=bhome.create();
               enum=(Enumeration)bid.getNewItemList();
          } else {
               TestNewTreeData tntd= new TestNewTreeData();
               enum=tntd.results();
          }
          while((enum !=null) && (enum.hasMoreElements())) {
             while(enum.hasMoreElements()) {
                AuctionItem auctionItem=(AuctionItem)enum.nextElement();
                newItems.addElement(new Integer(auctionItem.getId())); 
             }
          }
          if (!standaloneMode) {
              enum=(Enumeration)bid.getClosedItemList();
          } else {
              TestClosedTreeData tctd= new TestClosedTreeData();
              enum=tctd.results();
          }
          while((enum !=null) && (enum.hasMoreElements())) {
             while(enum.hasMoreElements()) {
                AuctionItem auctionItem=(AuctionItem)enum.nextElement();
                closedItems.addElement(new Integer(auctionItem.getId())); 
             }
          }
       } catch (Exception e) {
           System.out.println("AuctionServlet <list>:"+e);
       }                                     

       nodes = new DefaultMutableTreeNode[treelabels.length];
       DefaultMutableTreeNode[] closednodes = new 
		DefaultMutableTreeNode[closedItems.size()];                                               
       DefaultMutableTreeNode[] newnodes = new 
		DefaultMutableTreeNode[newItems.size()];
       for (int i=0; i<treelabels.length; i++) {
           nodes[i] = new DefaultMutableTreeNode(treelabels[i]);
       }
       nodes[0].add(nodes[1]);
       nodes[0].add(nodes[2]);
 
       for (int i=0; i<closedItems.size(); i++) {
           closednodes[i] = new 
		DefaultMutableTreeNode(closedItems.elementAt(i));
           nodes[1].add(closednodes[i]);
       }
 
       for (int i=0; i<newItems.size(); i++) {
           newnodes[i] = new 
		DefaultMutableTreeNode(newItems.elementAt(i));
           nodes[2].add(newnodes[i]);
       }                                                           
       DefaultTreeModel model=new DefaultTreeModel(nodes[0]);
 
       tree = new JTree(model);
 
       JScrollPane scroll = new JScrollPane(tree);
       browsePanel.add(scroll, BorderLayout.CENTER);
       findPanel= new JPanel();
       findField= new JTextField(10);
       findButton= new JButton("find");
       findButton.addActionListener (new ActionListener() {
            public void actionPerformed (ActionEvent e) {
               String field=findField.getText();
               if(field != null) {
                   findNode(findField.getText());
               } else {
                   return;
               }
            }
       });                                   
       findPanel.add(findField);
       findPanel.add(findButton);
       browsePanel.add(findPanel, BorderLayout.SOUTH);
       frame.setSize(300,350);         
    }

    private void findNode(String field) {
         Enumeration e = nodes[0].depthFirstEnumeration();
         Object currNode;
         while (e.hasMoreElements()) {
             currNode = e.nextElement();
             if(currNode.toString().equals(field)) {
                 TreePath path=new TreePath(((
			DefaultMutableTreeNode)currNode).getPath());
                 tree.makeVisible(path);
                 tree.setSelectionRow(tree.getRowForPath(path)); 
                 return;
             }
         }
     }                                 

    public static void main(String args[]) {
        AuctionClient ac= new AuctionClient();
    }
}

class CustomRenderer extends DefaultTableCellRenderer {
   public Component getTableCellRendererComponent(JTable table,
               Object value, boolean isSelected, boolean hasFocus, 
                           int row, int column) {
       Component comp = super.getTableCellRendererComponent
                       (table,value,isSelected,hasFocus,row,column);

       JLabel label = (JLabel)comp;
       if(((Integer)value).intValue() >= 30) {         
           label.setIcon(new ImageIcon("Hot.gif")); 
       } else {
           label.setIcon(new ImageIcon("Normal.gif")); 
       }
       return (JLabel)label;
   }
}

class CustomButtonEditor extends DefaultCellEditor {
     
    final JButton mybutton;
    JFrame frame;

    CustomButtonEditor(JFrame frame) {
        super(new JCheckBox());
        mybutton = new JButton();
        this.editorComponent = mybutton;
        this.clickCountToStart = 2;
        this.frame=frame;
        mybutton.setOpaque(true);
        mybutton.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) {
              fireEditingStopped();
           }
        }); 
    }

    protected void fireEditingStopped() {
        super.fireEditingStopped(); 
    } 

    public Object getCellEditorValue() {
        JDialog jd= new JDialog(frame, "Time left");
        Calendar today=Calendar.getInstance();
        Calendar end=Calendar.getInstance();
        SimpleDateFormat in=new SimpleDateFormat("yyyy-MM-dd"); 
        try {
           end.setTime(in.parse(mybutton.getText()));
        } catch (Exception e){
           System.out.println("Error in date"+mybutton.getText()+e);
        }
        int days = 0; 
        while(today.before(end)) {
           today.roll(Calendar.DATE,true); 
           days++; 
        } 
        jd.setSize(200,100);
        if(today.after(end)) {
           jd.getContentPane().add(new JLabel("Auction completed"));
        } else {
           jd.getContentPane().add(new JLabel("Days left="+days));
        }
        jd.setVisible(true);
        
        return new String(mybutton.getText());
     }

    public Component getTableCellEditorComponent(JTable table, 
		Object value, boolean isSelected, int row, int column) {
        
      ((JButton) editorComponent).setText(((JButton)value).getText());
      if (isSelected) {
          ((JButton) editorComponent).setForeground(table.getSelectionForeground());
          ((JButton) editorComponent).setBackground(table.getSelectionBackground()); 
      } else {
          ((JButton) editorComponent).setForeground(table.getForeground());
          ((JButton) editorComponent).setBackground(table.getBackground()); 
      }
        return editorComponent;
    }                               
 }


class CustomButtonRenderer extends JButton implements TableCellRenderer {

    public CustomButtonRenderer() {
        setOpaque(true);
    }

    public Component getTableCellRendererComponent(JTable table,
                Object value, boolean isSelected, boolean hasFocus,
                int row, int column) {
      if (isSelected) {
         ((JButton)value).setForeground(table.getSelectionForeground());
         ((JButton)value).setBackground(table.getSelectionBackground()); 
      } else {
         ((JButton)value).setForeground(table.getForeground());
         ((JButton)value).setBackground(table.getBackground()); 
      }
      return (JButton)value;  
    }
}    

