/*
 * Copyright (C) 2013 Yoshinori Hayakawa <hayakawa@cite.tohoku.ac.jp>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package turtlemessenger;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.WindowConstants;


/**
 *
 * @author Yoshinori Hayakawa <hayakawa@cite.tohoku.ac.jp>
 */
public class TMVotingSummary extends javax.swing.JDialog {

     private TMController controller ;
     private PlottingCanvas canvas ;
     private int[] nchoices ;
     private UpdateThread thread ;
     private int width,height ;
    /**
     * Creates new form TMVotingResultsDialog
     */
    public TMVotingSummary(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        controller = (TMController) parent ;
        initComponents();
        
        canvas = new PlottingCanvas() ;
        graphPanel.add(canvas) ;
         
        nchoices = new int[10] ;
        for (int i=0 ; i<10 ; i++) nchoices[i] = 0 ;
        
        setLocationRelativeTo(parent) ;
        setResizable(true) ;
        
        setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                doneButtonActionPerformed(null) ;
            }
        });
        
        thread = new UpdateThread() ;
        thread.start();
    }

    public void updateNumbers() {
        controller.countVotes();
        for (int i=0; i<10; i++) {
            nchoices[i] = controller.nchoices[i] ;
        }        
    }
    
    
    /**
     * 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 initComponents() {

        graphPanel = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        doneButton = new javax.swing.JButton();
        enlargeButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Voting results");
        setMinimumSize(new java.awt.Dimension(400, 400));

        graphPanel.setToolTipText("投票数の割合が棒グラフで表示されます");
        graphPanel.setOpaque(false);
        graphPanel.setPreferredSize(new java.awt.Dimension(432, 350));

        org.jdesktop.layout.GroupLayout graphPanelLayout = new org.jdesktop.layout.GroupLayout(graphPanel);
        graphPanel.setLayout(graphPanelLayout);
        graphPanelLayout.setHorizontalGroup(
            graphPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 0, Short.MAX_VALUE)
        );
        graphPanelLayout.setVerticalGroup(
            graphPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 413, Short.MAX_VALUE)
        );

        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("turtlemessenger/TMBundle"); // NOI18N
        doneButton.setText(bundle.getString("DONE")); // NOI18N
        doneButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                doneButtonActionPerformed(evt);
            }
        });

        enlargeButton.setText(bundle.getString("ENLARGE")); // NOI18N
        enlargeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                enlargeButtonActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(376, Short.MAX_VALUE)
                .add(enlargeButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 127, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(18, 18, 18)
                .add(doneButton)
                .add(23, 23, 23))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(21, Short.MAX_VALUE)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(doneButton)
                    .add(enlargeButton))
                .addContainerGap())
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(graphPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 621, Short.MAX_VALUE)
            .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(graphPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 413, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
        );

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

    private void doneButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_doneButtonActionPerformed
//        try {
//            if (thread != null && thread.isAlive()) {
//                thread.interrupt();
//            }
//            Thread.sleep(100);
//        } catch (InterruptedException ex) {
//            ;
//        }
//        thread = null;
        // dispose() ;
        setVisible(false) ;
    }//GEN-LAST:event_doneButtonActionPerformed

    private void enlargeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_enlargeButtonActionPerformed
        Rectangle bounds = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();  
        this.setBounds(bounds);  
    }//GEN-LAST:event_enlargeButtonActionPerformed

   
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton doneButton;
    private javax.swing.JButton enlargeButton;
    private javax.swing.JPanel graphPanel;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration//GEN-END:variables

    class UpdateThread extends Thread {

        public UpdateThread() {
        }

        @Override
        public void run() {
            try {
                for (;;) {
                    updateNumbers() ;
                    width = graphPanel.getWidth();
                    height = graphPanel.getHeight();
                    canvas.setBounds(0, 0, width, height);
                    canvas.repaint();
                    sleep(2000);
                }
            } catch (InterruptedException ex) {
                ;
            }
        }
    }
    
    class PlottingCanvas extends Canvas {
        
        private Font bfont ;
        // private Font pfont ;
        private Font sfont ;
        private int prevHeight ;
      
        private Color brown ;
        
        PlottingCanvas() {
            prevHeight=0 ;
            brown = new Color(156, 93, 82) ;
        }
        
        private void drawStringRight(String str, int x, int y, Graphics g, Font font) {
            g.setFont(font);
            FontMetrics fm= g.getFontMetrics();
            int w = fm.stringWidth(str);
            g.drawString(str, x-w, y);
        }
        
        @Override
        public void paint(Graphics g) {            
            
            width = graphPanel.getWidth();
            height = graphPanel.getHeight() ;

            setBounds(0,0,width,height) ;
            
            setBackground(Color.white);
            
            if (height != prevHeight) {
                bfont = new Font(Font.SANS_SERIF, Font.BOLD, (int)(height/15.0)) ;
                // pfont = new Font(Font.SANS_SERIF, Font.PLAIN, height/15) ;
                sfont = new Font(Font.SANS_SERIF, Font.PLAIN, (int)(height/20.0)) ;
                prevHeight = height ;
            }
            
            g.setColor(Color.BLACK);
            g.setFont(bfont) ;
            double yofs = ((height/11.0)-(height/15.0))*0.5 ;
            g.drawString("TOTAL",(int)(width*0.05),(int)(height*1.0/11.0-yofs));
            g.drawString("1/YES",(int)(width*0.05),(int)(height*2.0/11.0-yofs));
            g.drawString("2/NO",(int)(width*0.05),(int)(height*3.0/11.0-yofs));
            g.drawString("3",(int)(width*0.05),(int)(height*4.0/11.0-yofs));
            g.drawString("4",(int)(width*0.05),(int)(height*5.0/11.0-yofs));
            g.drawString("5",(int)(width*0.05),(int)(height*6.0/11.0-yofs));
            g.drawString("6",(int)(width*0.05),(int)(height*7.0/11.0-yofs));
            g.drawString("7",(int)(width*0.05),(int)(height*8.0/11.0-yofs));
            g.drawString("8",(int)(width*0.05),(int)(height*9.0/11.0-yofs));
            g.drawString("9",(int)(width*0.05),(int)(height*10.0/11.0-yofs));
            g.drawString("0 / ?",(int)(width*0.05),(int)(height*11.0/11.0-yofs));
            
            g.setFont(sfont) ;
            g.drawString("0%", (int) (width*0.34),(int)(height*1.0/11.0-yofs)) ;
            g.drawString("50%", (int) (width*0.62),(int)(height*1.0/11.0-yofs)) ;
            g.drawString("100%", (int) (width*0.90),(int)(height*1.0/11.0-yofs)) ;
            
            float tot=0 ;
            for (int i=0 ; i<10 ; i++) tot += nchoices[i] ;
            
            g.setColor(Color.RED);
            drawStringRight(Integer.toString((int)tot),(int)(width*0.33),(int)(height*1.0/11.0-yofs), g, bfont);
            drawStringRight(Integer.toString(nchoices[1]),(int)(width*0.33),(int)(height*2.0/11.0-yofs), g, bfont);
            drawStringRight(Integer.toString(nchoices[2]),(int)(width*0.33),(int)(height*3.0/11.0-yofs), g, bfont);
            drawStringRight(Integer.toString(nchoices[3]),(int)(width*0.33),(int)(height*4.0/11.0-yofs), g, bfont);
            drawStringRight(Integer.toString(nchoices[4]),(int)(width*0.33),(int)(height*5.0/11.0-yofs), g, bfont);
            drawStringRight(Integer.toString(nchoices[5]),(int)(width*0.33),(int)(height*6.0/11.0-yofs), g, bfont);
            drawStringRight(Integer.toString(nchoices[6]),(int)(width*0.33),(int)(height*7.0/11.0-yofs), g, bfont);
            drawStringRight(Integer.toString(nchoices[7]),(int)(width*0.33),(int)(height*8.0/11.0-yofs), g, bfont);
            drawStringRight(Integer.toString(nchoices[8]),(int)(width*0.33),(int)(height*9.0/11.0-yofs), g, bfont);
            drawStringRight(Integer.toString(nchoices[9]),(int)(width*0.33),(int)(height*10.0/11.0-yofs), g, bfont);
            drawStringRight(Integer.toString(nchoices[0]),(int)(width*0.33),(int)(height*11.0/11.0-yofs), g, bfont);

            g.setColor(Color.LIGHT_GRAY);
            
            g.fillRect((int)(width*0.35), (int)(height/11.0), 
                    (int)(width*0.6), (int)(height*10/11.0));
            
            g.setColor(Color.DARK_GRAY);
            for (double x=width*0.35 ; x<width*0.95+1 ; x+=width*0.6/10.0) {
                g.drawLine((int)x, (int)(height/11.0), (int)x, height);
            }
            
            
            Color colors[] = {brown, Color.RED, Color.ORANGE, Color.YELLOW, Color.GREEN, 
                              Color.BLUE, Color.MAGENTA, Color.GRAY, Color.LIGHT_GRAY, Color.BLACK,} ;
            
            // g.setColor(Color.PINK);
            
            int cnt = 0 ;
            for (double y = height/11.0; y<height && cnt<10; y += height/11.0 , cnt++) {
                double barlen = 0 ;
                if (tot>0.0) {
                    int choice ;
                    if (cnt<=8) choice=cnt+1 ;  // 1, 2, 3 .... first
                    else choice=0 ;             // then 0 lastly
                    barlen = nchoices[choice]/tot*width*0.6 ;
                }
                
                g.setColor(colors[cnt]) ;
                g.fill3DRect((int)(width*0.35),(int)(y+yofs), 
                              (int) barlen, (int)(height/15.0), true);
            }
        }
    }
}
