/*
 * Main.java
 *
 * Created on 2008/12/15, 21:35:55
 */
package peca;

import java.awt.Color;
import java.awt.Component;
import java.awt.FontMetrics;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;

/**
 *
 * @author falloutboy
 */
public class Main extends javax.swing.JFrame {

    /** Creates new form Main */
    public Main() {
        getChannels();
        initComponents();
    }
    BuildChannelDataTableThread buildChannelDataTableThread;

    private String makePeCaHttpUrl(ChannelData d) {
        StringBuilder sb = new StringBuilder();
        sb.append("http://192.168.24.51:7144/pls/");
        sb.append(d.get(1));
        sb.append("?tip=");
        sb.append(d.get(2));
        return sb.toString();
    }

    private void getChannels() {
        try {
            if (buildChannelDataTableThread != null) {
                try {
                    buildChannelDataTableThread.join();
                } catch (InterruptedException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            buildChannelDataTableThread = null;
            buildChannelDataTableThread = new BuildChannelDataTableThread(new URL[]{
                        new URL("http://192.168.24.51:8080/http://kp.podzone.net/index.txt"),
                        new URL("http://192.168.24.51:8080/http://cp.webhop.net/index.txt"),});
            buildChannelDataTableThread.start();
        } catch (MalformedURLException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    RowColorSetting[] keywords = new RowColorSetting[]{
        new RowColorSetting() {

            String k = "トルティーノ|[Ss]akage|うたたね|のもてぃ|空戦型|あれくま|プログラミング|[Pp]rograming|[Pp]rogramming|[Jj]ava|JAVA|芝生|ぺぺ|料理|晩酌|KND|西村プラスチック";
            Pattern p = Pattern.compile(k);
            Color c = Color.GREEN;

            public String getKeyword() {
                return k;
            }

            public Pattern getPattern() {
                return p;
            }

            public Color getColor() {
                return c;
            }
        },
        new RowColorSetting() {

            String k = "映画|FPS|fps|ドラマ|[Mm]ovie|[Aa]nime|アニメ|AVA|L4D|水曜|カメラ|雑談|BGM|音楽";
            Pattern p = Pattern.compile(k);
            Color c = Color.ORANGE;

            public String getKeyword() {
                return k;
            }

            public Pattern getPattern() {
                return p;
            }

            public Color getColor() {
                return c;
            }
        }
    };

    TableModel getTableModel() {
        final List<String> _fav = new ArrayList<String>() {

            {
                add(("channelName"));
                // format is => [org title],colname1,colname2,...
                add(("[detail],description1,description2,playing1,playing2,playing3,playing4,comment"));
                add(("bitrate"));
                add(("type"));
            }
        };
        try {
            buildChannelDataTableThread.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
        return new ChannelTable(_fav, buildChannelDataTableThread.get(), keywords);
    }

    /** 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() {

        jPopupMenu1 = new javax.swing.JPopupMenu();
        jPopupMenuItem1 = new javax.swing.JMenuItem();
        jPopupMenuItem2 = new javax.swing.JMenuItem();
        jPopupMenuItem3 = new javax.swing.JMenuItem();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 =         new JTable() {

            @Override
            public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
                Component c = super.prepareRenderer(renderer, row, column);
                ChannelTable t = (ChannelTable) getModel();

                c.setForeground(getForeground());
                if (isRowSelected(row)) {
                    c.setBackground(getSelectionBackground());
                } else {
                    c.setBackground(getBackground());
                    for(RowColorSetting setting : t.keywords) {
                        boolean isMatched = setting.getPattern().matcher(t.data[row].getRaw()).find();
                        if (isMatched) {
                            c.setBackground(setting.getColor());
                            break;
                        }
                    }
                }
                return c;
            }
        };
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        updateMenu = new javax.swing.JMenuItem();

        jPopupMenu1.add(jPopupMenuItem1);
        jPopupMenu1.add(jPopupMenuItem2);
        jPopupMenu1.add(jPopupMenuItem3);

        jPopupMenuItem1.setText("copy");
        jPopupMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jPopupMenuItem1ActionPerformed(evt);
            }
        });

        jPopupMenuItem2.setText("contact");
        jPopupMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jPopupMenuItem2ActionPerformed(evt);
            }
        });

        jPopupMenuItem3.setText("url");
        jPopupMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jPopupMenuItem3ActionPerformed(evt);
            }
        });

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTable1.setModel(getTableModel());
        jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jTable1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTable1KeyPressed(evt);
            }
        });
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jTable1MousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jTable1MouseReleased(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);
        table_resize(jTable1);

        jMenu1.setText("File");

        jMenuItem1.setText("jMenuItem1");
        jMenu1.add(jMenuItem1);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");

        updateMenu.setText("update");
        updateMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updateMenuActionPerformed(evt);
            }
        });
        jMenu2.add(updateMenu);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 278, Short.MAX_VALUE)
        );

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

    private void jTable1MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseReleased
        table_popup(evt);
    }//GEN-LAST:event_jTable1MouseReleased

    private void jTable1MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MousePressed
        table_popup(evt);
    }//GEN-LAST:event_jTable1MousePressed

    private void jPopupMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jPopupMenuItem1ActionPerformed
        int row = jTable1.getSelectedRow();
        ChannelData data = ((ChannelTable) jTable1.getModel()).data[row];
        StringSelection select = new StringSelection(makeMmsUrl(data));
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(select, select);
    }//GEN-LAST:event_jPopupMenuItem1ActionPerformed

    private String makeMmsUrl(ChannelData d) {
        StringBuilder sb = new StringBuilder();
        sb.append("mms://192.168.24.51:7144/stream/");
        sb.append(d.get(1));
        sb.append(".wmv");
        return sb.toString();
    }

    private void updateMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateMenuActionPerformed
        getChannels();
        jTable1.setModel(getTableModel());
        jTable1.revalidate();
        jTable1.repaint();
        table_resize(jTable1);
    }//GEN-LAST:event_updateMenuActionPerformed

    private void jPopupMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jPopupMenuItem2ActionPerformed
        int row = jTable1.getSelectedRow();
        ChannelData data = ((ChannelTable) jTable1.getModel()).data[row];

        StringSelection select = new StringSelection(data.get(3));
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(select, select);
    }//GEN-LAST:event_jPopupMenuItem2ActionPerformed

    private void jPopupMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jPopupMenuItem3ActionPerformed
        int row = jTable1.getSelectedRow();
        ChannelData data = ((ChannelTable) jTable1.getModel()).data[row];

        StringSelection select = new StringSelection(makePeCaHttpUrl(data));
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(select, select);
    }//GEN-LAST:event_jPopupMenuItem3ActionPerformed

    private void jTable1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTable1KeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            int row = jTable1.getSelectedRow();
            final ChannelData data = ((ChannelTable) jTable1.getModel()).data[row];
            try {
                File app = new File("/Applications/");
                Runtime.getRuntime().exec(new String[]{"open", "Firefox.app", makePeCaHttpUrl(data)}, null, app);
                StringSelection select = new StringSelection(makeMmsUrl(data));
                Toolkit.getDefaultToolkit().getSystemClipboard().setContents(select, select);
                new Thread(new Runnable() {

                    public void run() {
                        new MPlayerGUI(makeMmsUrl(data));
                    }
                }).start();

            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_jTable1KeyPressed

    private void table_popup(java.awt.event.MouseEvent evt) {
        if (evt.isPopupTrigger()) {
            jPopupMenu1.show(evt.getComponent(), evt.getX(), evt.getY());
        }
    }

    void table_resize(JTable t) {
        // TODO max resizing length
        FontMetrics fm = t.getFontMetrics(t.getFont());
        int is = ((JComponent) t.getDefaultRenderer(Object.class)).getInsets().left + 1;
        for (int j = t.getColumnCount() - 1; j >= 0; j--) {
            int w = 0;
            for (int i = t.getRowCount() - 1; i >= 0; i--) {
                int ww = SwingUtilities.computeStringWidth(fm, t.getValueAt(i, j).toString());
                if (ww > w) {
                    w = ww;
                }
            }
            t.getColumnModel().getColumn(j).setPreferredWidth(w + is * 2);
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Main().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JMenuItem jPopupMenuItem1;
    private javax.swing.JMenuItem jPopupMenuItem2;
    private javax.swing.JMenuItem jPopupMenuItem3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JMenuItem updateMenu;
    // End of variables declaration//GEN-END:variables
}
