import java.awt.Component;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import javax.imageio.ImageIO;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
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;

import org.apache.log4j.Logger;

/**
 * window to manage jobs and launching stamping
 * @author 413
 *
 */
public class WindowManageJobs extends JFrame implements ActionListener 
{
	private static Logger logger = Logger.getLogger(WindowManageJobs.class);
	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
	private JLabel image;
	private JScrollPane imageBox;

	/**
	 * 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");
		image = new JLabel();
		imageBox = new JScrollPane(image);
		
		this.jobList=jobList;
		jobs = new JList<>(jobList);
		//JScrollPane listjobs = new JScrollPane(jobs);
		//jobList.setCellRenderer(new JobRenderer());		
		
        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);
				if (job.getLastPage() != null)
				{
	        		renderer.setText(job.getPDFSource().getName() + " <= " + job.getPDFStamp().getName() + " p " + job.getStartPage() + " to " + job.getLastPage()); 
				}
				else
				{
	        		renderer.setText(job.getPDFSource().getName() + " <= " + job.getPDFStamp().getName() + " || p " + job.getStartPage() + " to end"); 
				}
        		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, 0, 203, 203)
			        .addComponent(suprimer)
			        .addComponent(update)
			    	.addComponent(imageBox)
			    )
		    )
		);
		layout.linkSize(SwingConstants.HORIZONTAL, imageBox, ajouter, suprimer, update);
		layout.setVerticalGroup
		(
		    layout.createParallelGroup(GroupLayout.Alignment.LEADING)
	        .addGroup
	        (
				layout.createSequentialGroup()
			    .addGroup
			    (
			    	layout.createParallelGroup(GroupLayout.Alignment.LEADING)
			    	.addComponent(text1)
			    	.addComponent(listjobs)
				)
			    .addGroup
			    (
			    	layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
	                .addComponent(launch)
	                .addComponent(stop)
	                .addComponent(result)
		        )
		    )
	        .addGroup
	        (
	        	layout.createSequentialGroup()
		    	.addComponent(ajouter)
				.addComponent(suprimer)
				.addComponent(update)
		    	.addComponent(imageBox)
			)
		);
		


		//window settings
        setTitle("Manage jobs");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(700, 361);
        setLocationRelativeTo(null);
        setVisible(true);
        
        //listener
        ajouter.addActionListener(this);
        suprimer.addActionListener(this);
        update.addActionListener(this);
        launch.addActionListener(this);
        stop.addActionListener(this);
        result.addActionListener(this);
        
		TimerTask task = new TimerTask()
		{
			@Override
			public void run() 
			{
				if(ServiceController.isFinish())
				{
					launch.setEnabled(true);
					stop.setEnabled(false);
				}
				else
				{
					launch.setEnabled(false);
					stop.setEnabled(true);

					try
					{
						File moreRecentFile = null;
						Boolean exist = false;
						if(ServiceConfig.image.exists() && ServiceConfig.image.isDirectory())
						{
							File[] subfiles = ServiceConfig.image.listFiles();
							if( subfiles.length > 0 )
							{
								for (int i = 0; i < subfiles.length; i++)
								{
									File subfile = subfiles[i];
									if(subfiles[i].getName().endsWith("(result).jpg")==true)
									{
										if(exist)
										{
											if (subfile.lastModified() > moreRecentFile.lastModified())
												moreRecentFile = subfile;
											
										}
										else
										{
											moreRecentFile = subfile;
											exist=true;
										}
										
									}
								}
							}
						}
						if(exist)
						{
							BufferedImage i = ImageIO.read(moreRecentFile), temp = new BufferedImage(200, 200, BufferedImage.TRANSLUCENT);
							Graphics2D g2d = (Graphics2D) temp.createGraphics();
							g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
							g2d.drawImage(i, 0, 0, 200, 200, null);
							g2d.dispose();
							image.setIcon(new ImageIcon(temp));
							
						}
					}
					catch (IOException e2)
					{
						e2.printStackTrace();
					}
				}
			}	
		};
		
		Timer timer = new Timer();
		timer.scheduleAtFixedRate(task, 0, 1000);
}
	
	/**
	 * 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);
	}
}
