package de.lazyzero.kkMulticopterFlashTool.gui;

import static lu.tudor.santec.i18n.Translatrix._;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileFilter;

import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;

import de.lazyzero.kkMulticopterFlashTool.KKMulticopterFlashTool;
import de.lazyzero.kkMulticopterFlashTool.utils.Firmware;
import de.lazyzero.kkMulticopterFlashTool.utils.Icons;
import de.lazyzero.kkMulticopterFlashTool.utils.XmlReaderFirmwares;

public class FirmwarePanel extends JPanel implements ActionListener, PropertyChangeListener{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private XmlReaderFirmwares firmwareLoader;
	private KKMulticopterFlashTool parent;
	private JComboBox firmwareCombobox;
	private JButton reload;
	private JButton flash; 
	
	private Vector<Firmware> firmwares = new Vector<Firmware>();
	private TitledBorder firmwareBorder;
	private CellConstraints cc;
	private JLabel firmwareLabel;
	private JTextField firmwareFileField;
	private JButton flashFile;
	private Component firmwareFileLabel;
	private JButton load;
	private JFileChooser fc;
	private FileFilter ffilter;
	private File firmwareFile;

	public FirmwarePanel(KKMulticopterFlashTool parent,
			XmlReaderFirmwares firmwareLoader) {
		this.parent = parent;
		this.firmwareLoader = firmwareLoader;
		init();
		
		this.addPropertyChangeListener(this);
	}

	private void init() {
		fc = new JFileChooser(parent.getSettings().getProperty("last.dir","%HOME%"));
		fc.setFileSelectionMode(JFileChooser.FILES_ONLY);

		ffilter = new FileFilter() {
			
			@Override
			public String getDescription() {
				return "Hex-File (.hex)";
			}
		
			@Override
			public boolean accept(File f) {
				return f.isDirectory() || f.getAbsoluteFile().toString().toLowerCase().endsWith(".hex");
			}
		};
		
		fc.setFileFilter(ffilter);
		
		//create the CellContraints
		cc  = new CellConstraints();
		
		// create the Layout for Panel this
		String panelColumns = "pref,3dlu,fill:pref:grow,3dlu,pref,3dlu,pref";
		String panelRows = "pref,3dlu,pref";
		FormLayout panelLayout = new FormLayout(panelColumns, panelRows);
		this.setLayout(panelLayout);
		
		firmwareLabel = new JLabel(_("firmware"));
		firmwareFileLabel = new JLabel(_("firmware.file"));
		
		this.setBorder(new TitledBorder(_("firmware.settings")));
		
		firmwareFileField = new JTextField();
		
		firmwareCombobox = new JComboBox(firmwares);
		firmwareCombobox.setBorder(firmwareBorder);
		firmwareCombobox.addActionListener(this);
		
		reload = new JButton(Icons.getIcon16(Icons.RELOAD));
		reload.addActionListener(this);
		
		flash = new JButton(Icons.getIcon16(Icons.RUN));
		flash.addActionListener(this);
		flash.setEnabled(false);
		
		load = new JButton(Icons.getIcon16(Icons.LOAD));
		load.addActionListener(this);
		
		flashFile = new JButton(Icons.getIcon16(Icons.RUN));
		flashFile.addActionListener(this);
		flashFile.setEnabled(false);
		
		this.add(firmwareFileLabel, cc.xy(1, 1));
		this.add(firmwareFileField, cc.xy(3, 1));
		this.add(load, cc.xy(5,1));
		this.add(flashFile, cc.xy(7,1));
		this.add(new JSeparator(), cc.xyw(1, 2, 7));
		this.add(firmwareLabel, cc.xy(1, 3));
		this.add(firmwareCombobox, cc.xy(3,3));
		this.add(reload, cc.xy(5,3));
		this.add(flash, cc.xy(7,3));
	}

	@Override
	public void actionPerformed(ActionEvent action) {
		if (action.getSource().equals(reload)){
			parent.clearText();
			firmwareCombobox.removeAllItems();
			parent.println(_("messages.reloadList"));
			
			try {
				firmwareLoader.readXmlFile(firmwareLoader.getURL());
			} catch (Exception e) {
				parent.println(_("messages.reloadList.error"));
				e.printStackTrace();
				return;
			}
			
			String controllerName = parent.getController().getCaption();
			firmwares = firmwareLoader.getFirmwares(controllerName);
			
			if (KKMulticopterFlashTool.isOfflineMode()){
				firmwares = Firmware.getOfflineAvailableFirmwares(firmwares);
			}
			
			parent.println(_("messages.reloadList.done"));
			
			System.out.println("firmwares loaded: " + firmwares.size());
			for (int i = 0; i < firmwares.size(); i++) {
				firmwareCombobox.addItem(firmwares.get(i));
			}
			if (firmwareCombobox.getItemCount()>0){
				firmwareCombobox.setSelectedIndex(0);
				flash.setEnabled(true);
			} else {
				flash.setEnabled(false);
			}
		}
		
		if (action.getSource().equals(flash)){
			parent.clearText();
			parent.println(_("messages.flashRepository"));
			firmwareFile = ((Firmware)firmwareCombobox.getSelectedItem()).getFile(); 
			parent.setFirmware(firmwareFile);
			parent.flashAVR();
		}
		
		if (action.getSource().equals(load)){

			if (action.getSource().equals(load)) {
				int returnVal = fc.showOpenDialog(this);

				if (returnVal == JFileChooser.APPROVE_OPTION) {
					firmwareFile = fc.getSelectedFile();
					// This is where a real application would open the file.
					firmwareFileField.setText(firmwareFile.getName());
					parent.setFirmware(firmwareFile);
					parent.clearText();
					parent.println(_("messages.loadFile"));
					flashFile.setEnabled(true);
				} else {
					firmwareFileField.setText("");
					parent.clearText();
					parent.println(_("messages.nothingLoad"));
					flashFile.setEnabled(false);
				}
			}
			
		}
		
		if (action.getSource().equals(flashFile)){
			parent.clearText();
			parent.println(_("messages.flashFile"));
			parent.flashAVR();
		}
		
	}

	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		if (evt.getPropertyName().equals(ControllerPanel.CONTROLLER_CHANGED)) {
			reload.doClick();
		}
	}

}
