/*
 * PS3 Media Server, for streaming any medias to your PS3.
 * Copyright (C) 2008  A.Brochard
 *
 * 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; version 2
 * of the License only.
 *
 * 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, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package net.pms.newgui;

import java.awt.Component;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Locale;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.JPopupMenu;
import javax.swing.JMenuItem;
import javax.swing.JFileChooser;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

import net.pms.Messages;
import net.pms.PMS;
import net.pms.configuration.PmsConfiguration;
import net.pms.configuration.Build;
import net.pms.external.ExternalFactory;
import net.pms.external.ExternalListener;
import net.pms.util.KeyedComboBoxModel;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.factories.Borders;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.sun.jna.Platform;

public class rz_AudioImageTab {
	private static final Logger logger = LoggerFactory.getLogger(GeneralTab.class);
	//private JCheckBox ckbox1;
	
	//---- web transcode settings 
	//for Java7
	//private JComboBox sel_type;
	//private JComboBox play_type_iav;
	private JComboBox<String> sel_type;
	private JComboBox<String> play_type_iav;
	
	private JTextField dp_width;
	private JTextField dp_height;
	private JTextField dp_interval;
	private JTextField dp_interval_iav;
	private JCheckBox cbtn_aav;
	private JCheckBox cbtn_aav_cap;
	private JCheckBox cbtn_iav;
	private JCheckBox cbtn_iav_cap;
	private JCheckBox cbtn_iav_gap;

	//---- web search 
	private JTextField txf_path1;
	private JTextField txf_path2;
	private JTextField txf_path1_iav;
	private JTextField txf_path2_iav;

	private JPanel pPlugins;
	private final PmsConfiguration configuration;
	
	private ArrayList<String[]> sc_defaults = new ArrayList<String[]>();
	private ArrayList<String[]> ch_defaults = new ArrayList<String[]>();
	
	private String[] sel_typet		=  {"Genre","Artist","Album","Title","All"};	//for AAV SelectionBox
	private String[] play_typet_iav	=  {"Single","Slideshow"};	//for IAV SelectionBox
	
	rz_AudioImageTab(PmsConfiguration configuration) {
		this.configuration = configuration;
	}
	
	public void setClipPath1(String path,int clip_type) {
		if(clip_type==1) {  //aav
			txf_path1.setText(path);
			configuration.setRZ_aav_clip_path1(path);
		}
		else {	//iav
			txf_path1_iav.setText(path);
			configuration.setRZ_iav_clip_path1(path);
		}
	}
	public void setClipPath2(String path,int clip_type) {
		if(clip_type==1) {  //audio
			txf_path2.setText(path);
			configuration.setRZ_aav_clip_path2(path);
		}
		else {
			txf_path2_iav.setText(path);
			configuration.setRZ_iav_clip_path2(path);
		}
	}
	public String getClipSelectBy() {
		int i=configuration.getRZ_aav_clip_seltype();
		return sel_typet[i];
	}
	public String getPlayTypeIAV() {
		int i=configuration.getRZ_iav_clip_seltype();
		return play_typet_iav[i];
	}

	public JComponent build() {
		int ypos,ypos_sv,xpos;
		int xpos_lb;	//1st, label
		int xpos_tf;	//2nd, textfield
		int xpos_bt;	//3rd, button
		int width_tf;	//width of textfield
		int width_tt;	//width of title line

		//---- Layout
		/*
		------------------------------------------------------------------------------------------
		com.jgoodies.forms.layout.FormLayout by JGoodies form layout implementation 
		The resize behavior is defined by a non-negative resize weight. 
		The syntax for the string representation for columns and rows is as follows: 
		------------------------------------------------------------------------------------------
		Spec 1: Column and Row String Encoding Syntax 
		------------------------------------------------------------------------------------------
		columnSpec            ::=   [columnAlignment:] size [:resizeBehavior] 
		rowSpec               ::=   [rowAlignment :] size [:resizeBehavior] 
		columnAlignment       ::=   LEFT | CENTER | RIGHT | FILL | L | C | R | F 
		rowAlignment          ::=   TOP | CENTER | BOTTOM | FILL | T | C | B | F 
		size                  ::=   constantSize | componentSize | boundedSize 
		componentSize         ::=   MIN | PREF | DEFAULT | M | P | D 
		constantSize          ::=   <integer>integerUnit | <double>doubleUnit 
		integerUnit           ::=   PX | PT | DLU 
		doubleUnit            ::=   IN | MM | CM 
		boundedSize           ::=   MIN(constantSize;componentSize)| MAX(constantSize;componentSize) 
		resizeBehavior        ::=   NONE | GROW | GROW(<double>) | G(<double>)
		------------------------------------------------------------------------------------------
		Spec 2: Cell Constraints String Encoding Syntax 
		------------------------------------------------------------------------------------------
		constraints 	::= column, row [, colSpan, rowSpan][, hAlign, vAlign] 
		column			::= <integer> 
		row 			::= <integer> 
		colSpan 		::= <integer> 
		rowSpan 		::= <integer> hAlign ::= LEFT | CENTER | RIGHT | DEFAULT | FILL | L | C | R | D | F 
		vAlign 			::= TOP | CENTER | BOTTOM | DEFAULT | FILL | T | C | B | D | F
		------------------------------------------------------------------------------------------
		<Notes>
		------------------------------------------------------------------------------------------
		pref is for 'preferred size'
		min is for  'minimum size', 
		dlu is a size unit that scales with the font.
		------------------------------------------------------------------------------------------
		*/

		FormLayout layout = new FormLayout(	
			// define mesh type layout
			// 1st string: define_columns
			//   1        2     3  4      5  6     7  8     9          10    11
			//"left:pref, 2dlu, p, 2dlu , p, 2dlu, p, 2dlu, pref:grow, 5dlu, p", 
			// 1        2  3  4  5  6  7  8  9  10 11 12 13 14 15 16 17 18      19    20
			"left:p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, p:grow, 5dlu, p", 
			// 2nd string: define_rows
			"p,3dlu, p,3dlu, p,3dlu, p,3dlu, p,3dlu, p,3dlu, p,3dlu, p,3dlu, p,3dlu, p,3dlu, p,3dlu, p,3dlu, p,3dlu, p,3dlu, p,3dlu, p,3dlu, p,3dlu, p,3dlu, p,3dlu, p,3dlu, p");
		
		PanelBuilder builder = new PanelBuilder(layout);
		builder.setBorder(Borders.DLU4_BORDER);
		builder.setOpaque(true);

		CellConstraints cc = new CellConstraints();
		
		//---- set Initial_data(defaults) to PMS global
		xpos_lb=1;		//1st, label
		xpos_tf=3;		//2nd, textfield
		xpos_bt=20;		//3rd, button
		width_tf=16;	//width of textfield
		width_tt=20;	//width of title line
		
		//----------------------------------------------------------------------
		// Audio As Video
		//----------------------------------------------------------------------
		ypos=3;		//base y pos
		xpos=xpos_lb;
		//---- AAV separator
		JComponent sep_tr = builder.addSeparator("AudioAsVideo Settings", cc.xyw(1, ypos, width_tt));
		sep_tr = (JComponent) sep_tr.getComponent(0);
		sep_tr.setFont(sep_tr.getFont().deriveFont(Font.BOLD));
		
		//---- AAV Enable AAV (checkbox)
		ypos+=2;
		xpos=xpos_lb;
		cbtn_aav=new JCheckBox("Enable AudioAsVideo   ");
		cbtn_aav.addActionListener(new ActionListener () {
			@Override
			public void actionPerformed(ActionEvent e) {
				configuration.setRZ_audio_as_video(cbtn_aav.isSelected());
				PMS.rz_is_audio_as_video=cbtn_aav.isSelected();
			}		
		});
		builder.add(cbtn_aav, cc.xy(xpos, ypos));
		if(configuration.isRZ_audio_as_video()) cbtn_aav.setSelected(true);
		else cbtn_aav.setSelected(false);

		//---- AAV Enable Caption (checkbox)
		xpos+=2;
		cbtn_aav_cap=new JCheckBox("Disp Caption ");
		cbtn_aav_cap.addActionListener(new ActionListener () {
			@Override
			public void actionPerformed(ActionEvent e) {
				configuration.setRZ_aav_caption(cbtn_aav_cap.isSelected());
			}		
		});
		builder.add(cbtn_aav_cap, cc.xy(xpos, ypos));
		if(configuration.isRZ_aav_caption()) cbtn_aav_cap.setSelected(true);
		else cbtn_aav_cap.setSelected(false);

		//---- AAV Resize_w/h (textfield x2)
		xpos=7;
		//builder.addLabel(": ", cc.xy(xpos, ypos));
		builder.addLabel("   Video Scale Width:", cc.xy(xpos, ypos));
		dp_width = new JTextField(6);
		builder.add(dp_width, cc.xyw(xpos+=2, ypos, 1));
		int w=configuration.getRZ_aav_resize_w();
		dp_width.setText(""+w);
		dp_width.addActionListener(new ActionListener () {
			@Override
			public void actionPerformed(ActionEvent e) {
				int w=Integer.parseInt(dp_width.getText());
				configuration.setRZ_aav_resize_w(w);
				//PMS.dbg("resize_w="+w);
			}		
		});

		builder.addLabel("    Height: ", cc.xy(xpos+=2, ypos));
		dp_height = new JTextField(6);
		builder.add(dp_height, cc.xyw(xpos+=2, ypos, 1));
		int h=configuration.getRZ_aav_resize_h();
		dp_height.setText(""+h);
		dp_height.addActionListener(new ActionListener () {
			@Override
			public void actionPerformed(ActionEvent e) {
				int h=Integer.parseInt(dp_height.getText());
				configuration.setRZ_aav_resize_h(h);
			}		
		});
		
		//---- AAV Selection Method
		ypos+=2;
		xpos=xpos_lb;
		builder.addLabel("VisualClip Select By ", cc.xy(xpos+0, ypos));
		//sel_type = new JComboBox(sel_typet);
		sel_type = new JComboBox<String>(sel_typet); //for Java7
		
		builder.add(sel_type, cc.xy(xpos+=2, ypos));
		int i=configuration.getRZ_aav_clip_seltype();
		sel_type.setSelectedIndex(i);
		sel_type.addActionListener(new ActionListener () {
			@Override
			public void actionPerformed(ActionEvent e) {
				int i=sel_type.getSelectedIndex();
				//PMS.dbg("actionPerformed: sel="+i);
				configuration.setRZ_aav_clip_seltype(i);
			}
		});
		
		//---- AAV Change Interval
		builder.addLabel("   Change Interval (secs)", cc.xy(xpos+=4, ypos));
		dp_interval = new JTextField(6);
		builder.add(dp_interval, cc.xyw(xpos+=2, ypos, 1));
		int interval=configuration.getRZ_aav_clip_interval();
		dp_interval.setText(""+interval);
		dp_interval.addActionListener(new ActionListener () {
			@Override
			public void actionPerformed(ActionEvent e) {
				int interval=Integer.parseInt(dp_interval.getText());
				configuration.setRZ_aav_clip_interval(interval);
			}		
		});

		//---- AAV VisualClip path1
		ypos+=2;
		ypos_sv=ypos;	//for later use
		txf_path1 = new JTextField("");
		builder.addLabel("VisualClip Path 1", cc.xy(1, ypos));
		builder.add(txf_path1, cc.xyw(xpos_tf, ypos, width_tf));
		String s1=configuration.getRZ_aav_clip_path1();
		if(s1!=null) txf_path1.setText(s1);
		txf_path1.addActionListener(new ActionListener () {
			@Override
			public void actionPerformed(ActionEvent e) {
				configuration.setRZ_aav_clip_path1(txf_path1.getText());
			}		
		});
		
		//---- AAV Select dialog for path1
		JButton select1 = new JButton("Select Folder");
		builder.add(select1, cc.xy(xpos_bt, ypos));
		select1.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				JFileChooser chooser = null;
				try {
					chooser = new JFileChooser();
				} catch (Exception ee) {
					chooser = new JFileChooser(new RestrictedFileSystemView());
				}
				chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				int returnVal = chooser.showDialog((Component) e.getSource(), Messages.getString("FoldTab.28"));
				if (returnVal == JFileChooser.APPROVE_OPTION) {
					txf_path1.setText(chooser.getSelectedFile().getAbsolutePath());
					configuration.setRZ_aav_clip_path1(chooser.getSelectedFile().getAbsolutePath());
				}
			}
		});

		//---- AAV VisualClip path2
		ypos+=2;
		txf_path2 = new JTextField("");
		builder.addLabel("VisualClip Path 2", cc.xy(1, ypos));
		builder.add(txf_path2, cc.xyw(xpos_tf, ypos, width_tf));
		String s2=configuration.getRZ_aav_clip_path2();
		if(s2!=null) txf_path2.setText(s2);
		txf_path2.addActionListener(new ActionListener () {
			@Override
			public void actionPerformed(ActionEvent e) {
				configuration.setRZ_aav_clip_path2(txf_path2.getText());
			}		
		});
		
		//---- AAV Select dialog for path2
		JButton select2 = new JButton("Select Folder");
		builder.add(select2, cc.xy(xpos_bt, ypos));
		select2.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				JFileChooser chooser = null;
				try {
					chooser = new JFileChooser();
				} catch (Exception ee) {
					chooser = new JFileChooser(new RestrictedFileSystemView());
				}
				chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				int returnVal = chooser.showDialog((Component) e.getSource(), Messages.getString("FoldTab.28"));
				if (returnVal == JFileChooser.APPROVE_OPTION) {
					txf_path2.setText(chooser.getSelectedFile().getAbsolutePath());
					configuration.setRZ_aav_clip_path2(chooser.getSelectedFile().getAbsolutePath());
				}
			}
		});
		
		//----------------------------------------------------------------------
		// Image As Video
		//----------------------------------------------------------------------
		//---- dummy spacer
		ypos+=2;
		builder.addLabel(" ", cc.xy(xpos, ypos));
		
		//---- IAV main separator
		ypos+=2;
		JComponent sep_tr5 = builder.addSeparator("ImageAsVideo Settings", cc.xyw(1, ypos, width_tt));
		sep_tr5 = (JComponent) sep_tr5.getComponent(0);
		sep_tr5.setFont(sep_tr5.getFont().deriveFont(Font.BOLD));

		//---- Enable IAV (checkbox)
		ypos+=2;
		xpos=xpos_lb;
		cbtn_iav=new JCheckBox("Enable ImageAsVideo  ");
		cbtn_iav.addActionListener(new ActionListener () {
			@Override
			public void actionPerformed(ActionEvent e) {
				configuration.setRZ_image_as_video(cbtn_iav.isSelected());
				PMS.rz_is_image_as_video=cbtn_iav.isSelected();
			}		
		});
		builder.add(cbtn_iav, cc.xy(xpos, ypos));
		if(configuration.isRZ_image_as_video()) cbtn_iav.setSelected(true);
		else cbtn_iav.setSelected(false);
		
		//---- IAV Enable Caption (checkbox)
		xpos+=2;
		cbtn_iav_cap=new JCheckBox("Disp Caption ");
		cbtn_iav_cap.addActionListener(new ActionListener () {
			@Override
			public void actionPerformed(ActionEvent e) {
				configuration.setRZ_iav_caption(cbtn_iav_cap.isSelected());
			}		
		});
		builder.add(cbtn_iav_cap, cc.xy(xpos, ypos));
		if(configuration.isRZ_iav_caption()) cbtn_iav_cap.setSelected(true);
		else cbtn_iav_cap.setSelected(false);

		//---- IAV play mode
		ypos+=2;
		xpos=xpos_lb;
		builder.addLabel("Play mode ", cc.xy(xpos+0, ypos));
		play_type_iav = new JComboBox<String>(play_typet_iav);
		builder.add(play_type_iav, cc.xy(xpos+=2, ypos));
		i=configuration.getRZ_iav_clip_seltype();
		play_type_iav.setSelectedIndex(i);
		play_type_iav.addActionListener(new ActionListener () {
			@Override
			public void actionPerformed(ActionEvent e) {
				int i=play_type_iav.getSelectedIndex();
				//PMS.dbg("actionPerformed: sel="+i);
				configuration.setRZ_iav_clip_seltype(i);
			}
		});
		
		//---- IAV Change Interval
		builder.addLabel("   Change Interval (secs)", cc.xy(xpos+=4, ypos));
		dp_interval_iav = new JTextField(6);
		builder.add(dp_interval_iav, cc.xyw(xpos+=2, ypos, 1));
		interval=configuration.getRZ_iav_clip_interval();
		dp_interval_iav.setText(""+interval);
		dp_interval_iav.addActionListener(new ActionListener () {
			@Override
			public void actionPerformed(ActionEvent e) {
				int interval=Integer.parseInt(dp_interval_iav.getText());
				configuration.setRZ_iav_clip_interval(interval);
			}		
		});
		
		//---- IAV Gappless play
		xpos+=4;
		cbtn_iav_gap=new JCheckBox("Gapless play (test implement)");
		cbtn_iav_gap.addActionListener(new ActionListener () {
			@Override
			public void actionPerformed(ActionEvent e) {
				configuration.setRZ_iav_gapless(cbtn_iav_gap.isSelected());
			}		
		});
		builder.add(cbtn_iav_gap, cc.xy(xpos, ypos));
		if(configuration.isRZ_iav_gapless()) cbtn_iav_gap.setSelected(true);
		else cbtn_iav_gap.setSelected(false);

		//---- IAV AudioClip path1
		ypos+=2;
		ypos_sv=ypos;	//for later use
		txf_path1_iav = new JTextField("");
		builder.addLabel("AudioClip Path 1", cc.xy(1, ypos));
		builder.add(txf_path1_iav, cc.xyw(xpos_tf, ypos, width_tf));
		s1=configuration.getRZ_iav_clip_path1();
		if(s1!=null) txf_path1_iav.setText(s1);
		txf_path1_iav.addActionListener(new ActionListener () {
			@Override
			public void actionPerformed(ActionEvent e) {
				configuration.setRZ_iav_clip_path1(txf_path1_iav.getText());
			}		
		});
		
		//---- IAV Select dialog for path1
		JButton select1_iav = new JButton("Select Folder");
		builder.add(select1_iav, cc.xy(xpos_bt, ypos));
		select1_iav.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				JFileChooser chooser = null;
				try {
					chooser = new JFileChooser();
				} catch (Exception ee) {
					chooser = new JFileChooser(new RestrictedFileSystemView());
				}
				chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				int returnVal = chooser.showDialog((Component) e.getSource(), Messages.getString("FoldTab.28"));
				if (returnVal == JFileChooser.APPROVE_OPTION) {
					txf_path1_iav.setText(chooser.getSelectedFile().getAbsolutePath());
					configuration.setRZ_iav_clip_path1(chooser.getSelectedFile().getAbsolutePath());
				}
			}
		});
		
		//---- IAV AudioClip path2
		ypos+=2;
		ypos_sv=ypos;	//for later use
		txf_path2_iav = new JTextField("");
		builder.addLabel("AudioClip Path 2", cc.xy(1, ypos));
		builder.add(txf_path2_iav, cc.xyw(xpos_tf, ypos, width_tf));
		s1=configuration.getRZ_iav_clip_path2();
		if(s1!=null) txf_path2_iav.setText(s1);
		txf_path2_iav.addActionListener(new ActionListener () {
			@Override
			public void actionPerformed(ActionEvent e) {
				configuration.setRZ_iav_clip_path2(txf_path2_iav.getText());
			}		
		});
		
		//---- IAV Select dialog for path2
		JButton select2_iav = new JButton("Select Folder");
		builder.add(select2_iav, cc.xy(xpos_bt, ypos));
		select2_iav.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				JFileChooser chooser = null;
				try {
					chooser = new JFileChooser();
				} catch (Exception ee) {
					chooser = new JFileChooser(new RestrictedFileSystemView());
				}
				chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				int returnVal = chooser.showDialog((Component) e.getSource(), Messages.getString("FoldTab.28"));
				if (returnVal == JFileChooser.APPROVE_OPTION) {
					txf_path2_iav.setText(chooser.getSelectedFile().getAbsolutePath());
					configuration.setRZ_iav_clip_path2(chooser.getSelectedFile().getAbsolutePath());
				}
			}
		});
		
		//----------------------------------------------------------------------
		// Main panel
		//----------------------------------------------------------------------
		JPanel panel = builder.getPanel();
		JScrollPane scrollPane = new JScrollPane(
			panel,
			JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
			JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		return scrollPane;
	}
}
