package tmcsim.cadsimulator.viewer;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.nio.file.FileSystems;
import java.nio.file.Path;

import javax.swing.*;


/**
 * ConfigStatusPanel is a GUI object used for displaying the current configuration files.
 * 
 * @author Drew Miller
 * @version
 */
@SuppressWarnings("serial")
public class ConfigStatusPanel extends JPanel {
    
	private String[] configFileNames = {
			"cad_simulator_config.properties", 
			"cad_simulator_media_config.properties", 
			"cad_simulator_paramics_config.properties",
			"cad_simulator_smoketest_config.properties"
			};
	private JTextArea view;
    /**
     * Constructor.  Initialize data and GUI components.
     */
    public ConfigStatusPanel() {        
        initComponents();
    }
    
    private String getFileContent(Path pathToFile) throws IOException {
    	BufferedReader br = new BufferedReader(new FileReader(pathToFile.toString()));
    	String content = null;
    	String line = null;
    	while((line = br.readLine()) != null) {
    		content += line + "\n";
    	}
    	return content;
    }
    
    private Path getPathToFile(String fileName) {
    	Path p = FileSystems.getDefault().getPath("config", fileName); 
    	return p;
    }
   
	private void changeView(Path pathToFileName) {
		try {
        	view.setText(getFileContent(pathToFileName));
        	view.setCaretPosition(view.getDocument().getLength());
        } catch (IOException e) {
        	System.out.println("Error in setting text.");
        }
	}
    private void setupComboBox(JPanel container) {
        JComboBox selectMenu = new JComboBox(configFileNames);
        selectMenu.addActionListener(new ActionListener() {
        	public void actionPerformed(ActionEvent e) {
        		JComboBox b = (JComboBox)e.getSource();
        		System.out.println(b.getSelectedItem());
        		Path p = getPathToFile(b.getSelectedItem().toString());
        		changeView(p);
        	}

        });
        container.add(selectMenu);
    }
    
    private void setupTextView(JPanel container) {
        view = new JTextArea(15, 30);
        view.setEditable(false);
        view.setLineWrap(true);
        view.setWrapStyleWord(true);
        Path p = FileSystems.getDefault().getPath("config", configFileNames[0]);
        try {
        	view.setText(getFileContent(p));
        } catch (IOException e) {
        	System.out.println("Error in setting text.");
        }
        container.add(view);
    }
    /**
     * Initialize GUI components.
     */
    private void initComponents() {
        configTab = new JPanel(new FlowLayout(FlowLayout.CENTER));
        configTab.setPreferredSize(new Dimension(400, 400));
        setupComboBox(configTab);
        setupTextView(configTab);

        add(configTab);
    }
    
    
    private JPanel configTab;
    
}
