import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FilenameFilter;

import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;

/**
 * window to manage jobs and launching stamping
 * @author 413
 *
 */
public class WindowManageJobs extends JFrame implements ActionListener 
{
	private static final long serialVersionUID = 1L;
	private JList<Job> jobs;					//contain the list that contain the jobs
	private DefaultListModel<Job>jobList;		//the list that contain the jobs
	private JButton launch;						//Button to launch stamping
	private JButton stop;						//Button to stop stamping

	/**
	 * Constructor
	 * @param jobList
	 */
	public WindowManageJobs(DefaultListModel<Job> jobList) 
	{
    

		//Interface components
		JLabel text1 = new JLabel("Jobs:");
		JButton ajouter = new JButton("Add Job");
		JButton suprimer = new JButton("Delete Job");
		JButton update = new JButton("Update Job");
		JButton result = new JButton("Results");
		launch = new JButton("Run");
		stop = new JButton("Stop");
		
		this.jobList=jobList;
		jobs = new JList<>(jobList);
		//JScrollPane listjobs = new JScrollPane(jobs);
		//jobList.setCellRenderer(new JobRenderer());		
		
        JList<Job> jobs = new JList<>(jobList);
        JScrollPane listjobs = new JScrollPane(jobs);
        jobs.setCellRenderer(new ListCellRenderer<Job>()
        {
			protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
        	public Component getListCellRendererComponent(JList<? extends Job> list, Job job, int index, boolean isSelected, boolean cellHasFocus)
        	{
				JLabel renderer = (JLabel) defaultRenderer.getListCellRendererComponent(list, job, index, isSelected, cellHasFocus);
        		renderer.setText(job.getPDFSource().getName() + " <= " + job.getPDFStamp().getName() + " p " + job.getStartPage() + " to " + job.getLastPage()); 
        		return renderer;
        	}

        });
		
		//layout
		stop.setEnabled(false);
		GroupLayout layout = new GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setAutoCreateGaps(true);
		layout.setAutoCreateContainerGaps(true);
		layout.setHorizontalGroup
		(
			layout.createSequentialGroup()
		    .addComponent(text1)
		    .addGroup
		    (
		    	layout.createParallelGroup(GroupLayout.Alignment.LEADING)
		    	.addComponent(listjobs)
		    	.addGroup
		    	(
		    		layout.createSequentialGroup()
	    			.addComponent(launch)
	    			.addComponent(stop)
	    			.addComponent(result)
		    	)
	    	)
		    .addGroup
		    (
		    	layout.createParallelGroup(GroupLayout.Alignment.LEADING)
	    		.addGroup
	    		(
	    			layout.createParallelGroup(GroupLayout.Alignment.LEADING)
    				.addComponent(ajouter)
			        .addComponent(suprimer)
			        .addComponent(update)
			    )
		    )
		);
		layout.linkSize(SwingConstants.HORIZONTAL, ajouter, suprimer, update);
		layout.setVerticalGroup
		(
			layout.createSequentialGroup()
		    .addGroup
		    (
		    	layout.createParallelGroup(GroupLayout.Alignment.LEADING)
		    	.addComponent(text1)
		    	.addComponent(listjobs)
		        .addGroup
		        (
		        	layout.createSequentialGroup()
			    	.addComponent(ajouter)
					.addComponent(suprimer)
					.addComponent(update)
				)
			)
		    .addGroup
		    (
		    	layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(launch)
                .addComponent(stop)
                .addComponent(result)
	        )
		);
		


		//window settings
        setTitle("Manage jobs");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(600, 250);
        setLocationRelativeTo(null);
        setVisible(true);
        
        //listener
        ajouter.addActionListener(this);
        suprimer.addActionListener(this);
        update.addActionListener(this);
        launch.addActionListener(this);
        stop.addActionListener(this);
        result.addActionListener(this);
}
	
	/**
	 * return job list
	 * @return
	 */
	public DefaultListModel<Job> getL() {
		return jobList;
	}
	
	/**
	 * add the job in parameter to the list
	 * @param job
	 */
	public void add(Job job) 
	{
		jobList.addElement(job);
	}
	
	/**
	 * catch events
	 */
	public void actionPerformed(ActionEvent e) 
	{

		switch(e.getActionCommand())
		{
			case "Add Job" :
				new WindowJob(this);
				break;
				
			case "Delete Job" :
				if(jobs.isSelectionEmpty())
				{
					JOptionPane.showMessageDialog(null,"No job selected","impossible operation",JOptionPane.WARNING_MESSAGE);
				}
				else
				{
					int n = JOptionPane.showConfirmDialog(null,"Are you sure you want to delete this job?", "Delete", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
					if(n == 0)
					{
						jobList.getElementAt(jobs.getSelectedIndex()).getjobFile().delete();
						jobList.remove(jobs.getSelectedIndex());
					}
				}
				break;
				
			case "Update Job" :
				if(jobs.isSelectionEmpty())
				{
					JOptionPane.showMessageDialog(null,"No job selected","impossible operation",JOptionPane.WARNING_MESSAGE);
				}
				else
				{
					new WindowJob(this, jobs.getSelectedValue());
				}
				break;
				
			case "Run" :
				if(jobList.isEmpty())
				{
					JOptionPane.showMessageDialog(null, "No job to execute", "impossible operation", JOptionPane.WARNING_MESSAGE);
				}
				else
				{
					launch.setEnabled(false);
					stop.setEnabled(true);

					//delete folder Image Files
					File folder = ServiceConfig.image;
					File[] children = folder.listFiles();
					for(int i = 0; i < children.length; i++)
					{
						children[i].delete();
					}
					//delete folder Log Files
					folder = ServiceConfig.logs;
					children = folder.listFiles();
					for(int i = 0; i < children.length; i++)
					{
						children[i].delete();
					}
					//launch stamping
					ServiceController sc = new ServiceController();
					sc.run();
				}
				break;
				
			case "Stop" :
				int n = JOptionPane.showConfirmDialog(null, "Are you sure you want to stop the stamping?", "Stop", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
				if(n == 0)
				{
					ServiceController sc = new ServiceController();
					sc.stop();
				}
				launch.setEnabled(true);
				stop.setEnabled(false);
				break;
				
			case "Results" :
				new WindowResult();
				dispose();
				break;
				
			default :
				JOptionPane.showMessageDialog(null, "Unkonwn event happended :/");
			
		}
	}

	/**
	 * Starting
	 * @param args
	 */
	public static void main(String args[])
	{
		ServiceConfig.load();
		ServiceController.init();
		ServiceJob.init();
		//loading config.xml

		ServiceConfig.load();
		
		FilenameFilter filterXML = new FilenameFilter()
		{
			public boolean accept(File arg0, String arg1)
			{
				return arg1.endsWith(".xml");
			}
		};
		//Loading XML files
		DefaultListModel<Job> l = new DefaultListModel<Job>();
		File repertoire = ServiceConfig.job;
		File[] children = repertoire.listFiles(filterXML);
		for(int i = 0; i < children.length; i++)
		{
			l.addElement(Job.load(children[i]));
		}
		//creating the window
		new WindowManageJobs(l);
	}
}
