package com.example.rtguiapplication;

import java.awt.Desktop;

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

import java.io.InputStream;

import java.io.PrintWriter;

import java.io.RandomAccessFile;

import java.io.Serializable;

import java.util.Collection;

import java.util.HashSet;

import java.util.Iterator;

import java.util.Set;

import javax.swing.JFileChooser;

import javax.swing.filechooser.FileFilter;

import com.vaadin.annotations.AutoGenerated;

import com.vaadin.data.Item;

import com.vaadin.data.Property;

import com.vaadin.data.Property.ValueChangeEvent;

import com.vaadin.terminal.StreamResource;

import com.vaadin.terminal.StreamResource.StreamSource;

import com.vaadin.terminal.gwt.server.WebApplicationContext;

import com.vaadin.ui.Button;

import com.vaadin.ui.CheckBox;

import com.vaadin.ui.CustomComponent;

import com.vaadin.ui.Embedded;

import com.vaadin.ui.MenuBar;

import com.vaadin.ui.OptionGroup;

import com.vaadin.ui.Table;

import com.vaadin.ui.VerticalLayout;

import com.vaadin.ui.Window;

@SuppressWarnings("serial")

public class MeineMenubar extends CustomComponent implements Serializable {

@AutoGenerated

private VerticalLayout mainLayout;

private MenuBar menuBar;

private RtguiapplicationApplication rtguiapp;

private ParameterVerwaltung parameterVerwaltung;

private Window editorWindow;

PrintWriter stdout;

String line;

private Object[] meinZeileneintrag;

private LinkeLeiste_DL linkeleiste_dl;

private OptionGroup group;

private String meinhilfsstring;

/**

* The constructor should first build the main layout, set the composition

* root and then do any custom initialization.

*

* The constructor will not be automatically regenerated by the visual

* editor.

*

* @param linkeleiste_dl

*

* @param rtguiapp

* @param parameterVerwaltung

*/

public MeineMenubar(LinkeLeiste_DL linkeleiste_dl,

RtguiapplicationApplication rtguiapp,

ParameterVerwaltung parameterVerwaltung) {

this.rtguiapp = rtguiapp;

this.parameterVerwaltung = parameterVerwaltung;

this.linkeleiste_dl = linkeleiste_dl;

buildMainLayout();

setCompositionRoot(mainLayout);

// TODO add user code here

}

@SuppressWarnings("unused")

@AutoGenerated

private void buildMainLayout() {

// the main layout and components will be created here

mainLayout = new VerticalLayout();

menuBar = new MenuBar();

menuBar.setImmediate(false);

menuBar.setSizeFull();

com.vaadin.ui.MenuBar.MenuItem datei = menuBar.addItem("Datei", null,

null);

datei.addItem("Neue Datei", new MenuBar.Command() {

/**

*

*/

private static final long serialVersionUID = 7504160213633072775L;

public void menuSelected(MenuBar.MenuItem selectedItem) {

getApplication().close();

}

});

datei.addSeparator();

datei.addItem("Datei laden", new MenuBar.Command() {

/**

*

*/

private static final long serialVersionUID = 360218015440652438L;

public void menuSelected(MenuBar.MenuItem selectedItem) {

rtguiapp.laden();

}

});

datei.addItem("Datei speichern", new MenuBar.Command() {

/**

*

*/

private static final long serialVersionUID = -8816698725490329833L;

public void menuSelected(MenuBar.MenuItem selectedItem) {

rtguiapp.alleWindowsSpeichern();

}

});

datei.addSeparator();

datei.addItem("Beenden", new MenuBar.Command() {

/**

*

*/

private static final long serialVersionUID = 2419334254742931562L;

public void menuSelected(MenuBar.MenuItem selectedItem) {

getApplication().close();

getApplication()

.setLogoutURL("

}

});

datei.addItem("Editor öffnen", new MenuBar.Command() {

/**

*

*/

private static final long serialVersionUID = 2419334254742931562L;

public void menuSelected(MenuBar.MenuItem selectedItem) {

/*

* WebApplicationContext context = (WebApplicationContext)

* getApplication() .getContext();

*

* File webinfFolder = new File(context.getHttpSession()

* .getServletContext().getRealPath("WEB-INF/Editor1.csv"));

*

* getApplication().getMainWindow().showNotification(

* webinfFolder.getAbsolutePath());

*

* try { Desktop.getDesktop().open(webinfFolder); } catch

* (IOException e) { // TODO Auto-generated catch block

* e.printStackTrace(); }

*/

try {

editorSignals();

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

});

com.vaadin.ui.MenuBar.MenuItem optionen = menuBar.addItem("Optionen",

new MenuBar.Command() {

@Override

public void menuSelected(

com.vaadin.ui.MenuBar.MenuItem selectedItem) {

// TODO Auto-generated method stub

}

});

// Erstelle Config-Datei aus den zuvor erstellten / geänderten

// Diagrammen (Auswertungen)

com.vaadin.ui.MenuBar.MenuItem matlabConfig = menuBar.addItem(

"MatLab-Config", null, null);

matlabConfig.addItem("MatLab-Config öffnen", new MenuBar.Command() {

@Override

public void menuSelected(com.vaadin.ui.MenuBar.MenuItem selectedItem) {

Window window = new Window("MatLab-Config");

window.setHeight("650px");

window.setWidth("1200px");

window.setPositionX(150);

window.setPositionY(20);

StreamSource s = new StreamResource.StreamSource() {

@Override

public InputStream getStream() {

try {

File f = new File("C://RtGuiConfig//"

+ parameterVerwaltung.getDateiName());

FileInputStream fis = new FileInputStream(f);

return fis;

} catch (Exception e) {

e.printStackTrace();

return null;

}

}

};

StreamResource r = new StreamResource(s, parameterVerwaltung

.getDateiName(), mainLayout.getApplication());

System.out.println("öffne datei:"

+ parameterVerwaltung.getDateiName());

r.setCacheTime(0);

try {

Embedded e = new Embedded();

e.setSizeFull();

e.setHeight("550px");

e.setType(Embedded.TYPE_BROWSER);

// r.setMIMEType("application/txt");

e.setSource(r);

window.addComponent(e);

getApplication().getMainWindow().addWindow(window);

} catch (Exception dateiNichtVorhanden) {

System.out.println("Bitte zunächst Config-Datei erstellen");

}

}

});

matlabConfig.addItem("MatLab-Config speichern", new MenuBar.Command() {

@Override

public void menuSelected(com.vaadin.ui.MenuBar.MenuItem selectedItem) {

// Ggfs. zuvor erstellte Hashmaps löschen und Zaehler resetten

parameterVerwaltung.getApplikationsHashmap().clear();

parameterVerwaltung.getGesamteConfigHashmap().clear();

parameterVerwaltung.setZaehlerAlleParameterHashmaps(0);

parameterVerwaltung.setSortierer(1);

parameterVerwaltung.setTitel("");

parameterVerwaltung.setAlterTitel("");

Set<Window> set = rtguiapp.getMainWindow().getChildWindows();

parameterVerwaltung.erstelleApplikationsHashmap(set,

linkeleiste_dl);

}

});

mainLayout.addComponent(menuBar);

}

public void editorSignals() throws FileNotFoundException {

/* Erzeugung eines Subwindows der die Editortabelle enthält */

editorWindow = new Window();

editorWindow.setHeight("700px");

editorWindow.setWidth("1000px");

editorWindow.setPositionX(400);

editorWindow.setPositionY(200);

editorWindow.setCaption("Signaleditor");

editorWindow.setStyleName("editorWindow");

editorWindow.setResizable(false);

editorWindow.setModal(true);

editorWindow.setScrollable(false);

// editorWindow.setSizeFull();

/* Definition der Tabellen- Spaltennamen sowie dazugehöriger Datentypen */

final Table table = new Table();

table.setImmediate(true);

table.addContainerProperty("RT- GUI Bezeichnung", String.class, null);

table.addContainerProperty("INCA", String.class, null);

table.addContainerProperty("Steuergeraetauswahl", OptionGroup.class,

null);

table.addContainerProperty("Min", Double.class, null);

table.addContainerProperty("Low", Double.class, null);

table.addContainerProperty("High", Double.class, null);

table.addContainerProperty("Max", Double.class, null);

/* Tabelle mit Objekten füllen und Bearbeitung der Zeilen zulassen */

/*

* BufferedReader und FileReader Initialisierung (Momentan noch

* statisch, in Zukunft dynamisch)

*/

try {

BufferedReader br = new BufferedReader(new FileReader(

"config_signals.m"));

String line;

String[] signale = new String[7];

String etkc1;

String etkc2;

while ((line = br.readLine()) != null) {

if (line.contains("tempSignals.addSignal")) {

meinZeileneintrag = new Object[] { signale[0], signale[1],

signale[2], signale[3], signale[4], signale[5],

signale[6] };

int pos1 = line.indexOf("'");

String spalte1 = line.substring((pos1 + 1),

line.indexOf("'", pos1 + 2));

signale[0] = spalte1;

int pos2 = line.indexOf(",");

String spalte2 = line.substring((pos2 + 2),

line.indexOf("'", pos2 + 3));

/*

* if (spalte2.contains("_ETKC_1")) { spalte2 =

* spalte2.replace("_ETKC_1", ""); } if

* (spalte2.contains("_ETKC_2")) { spalte2 =

* spalte2.replace("_ETKC_2", ""); }

*/

// hängt an alle INCA-Strings das Steuergerät "ETKC_1" dran

/*

* if (spalte2.contains("_ETKC_1") ||

* spalte2.contains("_ETKC_2")) { }else{

*

* spalte2 = spalte2 +"_ETKC_1"; }

*/

signale[1] = spalte2;

System.out.println(spalte1 + spalte2);

signale[3] = "0";

signale[4] = "0";

signale[5] = "0";

signale[6] = "0";

table.addItem(meinZeileneintrag, null);

}

if (line.contains("tempSignal.set")) {

int pos1 = line.indexOf("{") + 1;

int pos2 = line.indexOf(",", pos1 + 1);

int pos3 = line.indexOf(",", pos2 + 1);

int pos4 = line.indexOf(",", pos3 + 1);

String schwelle1 = line.substring((pos1),

line.indexOf(",", pos1 + 1));

signale[3] = schwelle1;

String schwelle2 = line.substring((pos2 + 1),

line.indexOf(",", pos2 + 2));

signale[4] = schwelle2;

String schwelle3 = line.substring((pos3 + 1),

line.indexOf(",", pos3 + 2));

signale[5] = schwelle3;

String schwelle4 = line.substring((pos4 + 1),

line.indexOf("}", pos4 + 2));

signale[6] = schwelle4;

}

// Arrays.fill(meinZeileneintrag, null);

// }

}

br.close();

}

catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

// table.addItem(new Object[] { "engineSpeed", line }, new Integer(1));

/*

* table.addItem(new Object[] { "airCharge", "rl_w" }, new Integer(2));

* table.addItem(new Object[] { "airChargeMax", "rlmxs_w" }, new

* Integer(3)); table.addItem(new Object[] { "angleThrottle", "wdkba_w"

* }, new Integer( 4)); table.addItem(new Object[] { "vehicleVelocity",

* "vfzg_w" }, new Integer(5)); table.addItem(new Object[] {

* "angleCamOut", "wnwa_w_ETKC_1" }, new Integer(6)); table.addItem(new

* Object[] { "angleCamOut2", "wnwa_w_ETKC_2" }, new Integer(7));

* table.addItem(new Object[] { "angleCamIn", "wnwe_w_ETKC_1" }, new

* Integer(8));

*/

table.setEditable(true);

table.setSizeFull();

// table.setColumnExpandRatio("Max", 3.0f);

table.setColumnWidth("RT- GUI Bezeichnung", 200);

table.setColumnWidth("INCA", 200);

table.setColumnWidth("Steuergeraetauswahl", 100);

table.setColumnWidth("Min", 60);

table.setColumnWidth("Low", 60);

table.setColumnWidth("High", 60);

table.setColumnWidth("Max", 60);

/*

* table.setColumnExpandRatio("Low", 3.0f);

* table.setColumnExpandRatio("High", 3.0f);

* table.setColumnExpandRatio("Min", 3.0f);

*/

table.setCacheRate(20);

table.setPageLength(10);

//

/* Zusätzliche Spalte generieren, die eine Checkbox enthält */

table.addGeneratedColumn("selected", new Table.ColumnGenerator() {

@Override

public Object generateCell(Table source, final Object itemId,

Object columnId) {

/*

* When the chekboc value changes, add/remove the itemId from

* the selectedItemIds set

*/

final Button cb = new Button("löschen",

new Button.ClickListener() {

@Override

public void buttonClick(Button.ClickEvent event) {

table.removeItem(itemId);

}

});

return cb;

}

});

table.addGeneratedColumn("steuergeraet", new Table.ColumnGenerator() {

private String meineVariable;

@Override

public Object generateCell(Table source, final Object itemId,

Object columnId) {

/*

* When the chekboc value changes, add/remove the itemId from

* the selectedItemIds set

*/

// OptionGroup

// Object

group = new OptionGroup("My Group");

group.setImmediate(true);

final Object etkc1 = "ETKC_1";

final Object etkc2 = "ETKC_2";

group.addItem(etkc1);

group.addItem(etkc2);

meineVariable = (String) table.getContainerProperty(itemId,

"INCA").getValue();

if (meineVariable != null) {

if (meineVariable.contains("ETKC_1")) {

group.select(etkc1);

}

if (meineVariable.contains("ETKC_2")) {

group.select(etkc2);

}

}

group.addListener(new Property.ValueChangeListener() {

public void valueChange(ValueChangeEvent event) {

if (event.getProperty().toString() == "ETKC_1") {

meinhilfsstring = table.getItem(itemId)

.getItemProperty("INCA").getValue()

.toString();

if (meinhilfsstring.contains("ETKC_2")) {

meinhilfsstring = meinhilfsstring.substring(0,

meinhilfsstring.length() - 7);

table.getItem(itemId).getItemProperty("INCA")

.setValue(meinhilfsstring);

}

if (meinhilfsstring.contains("ETKC_2")

|| meinhilfsstring.contains("ETKC_1")) {

} else {

meinhilfsstring = meinhilfsstring + "_ETKC_1";

table.getItem(itemId).getItemProperty("INCA")

.setValue(meinhilfsstring);

}

}

if (event.getProperty().toString() == "ETKC_2") {

meinhilfsstring = table.getItem(itemId)

.getItemProperty("INCA").getValue()

.toString();

if (meinhilfsstring.contains("ETKC_1")) {

meinhilfsstring = meinhilfsstring.substring(0,

meinhilfsstring.length() - 7);

table.getItem(itemId).getItemProperty("INCA")

.setValue(meinhilfsstring);

}

if (meinhilfsstring.contains("ETKC_2")

|| meinhilfsstring.contains("ETKC_1")) {

} else {

meinhilfsstring = meinhilfsstring + "_ETKC_2";

table.getItem(itemId).getItemProperty("INCA")

.setValue(meinhilfsstring);

}

}

}

});

return group;

}

});

/*

* Just some cosmetics : no caption for the checkboc, and make it the

* first column

*/

table.setColumnHeader("selected", "");

table.setVisibleColumns(new String[] { "RT- GUI Bezeichnung", "INCA",

"steuergeraet", "Min", "Low", "High", "Max", "selected" });

editorWindow.addComponent(table);

editorWindow.addComponent(new Button("Neue Zeile hinzufügen",

new Button.ClickListener() {

@Override

public void buttonClick(Button.ClickEvent event) {

table.addItem(new Object[] { "", "", null, 0, 0, 0, 0,

null },

new Integer((Integer) (table.lastItemId()))

.intValue() + 1);

}

}));

editorWindow.addComponent(new Button("Config- Signals speichern",

new Button.ClickListener() {

@Override

public void buttonClick(Button.ClickEvent event) {

// Double login = (Double) tf.getValue();

try {

FileWriter fw = new FileWriter(

"config_signals_test.m");

BufferedWriter bw = new BufferedWriter(fw);

bw.write("tempSignals=rb.get('signals');");

bw.newLine();

// Collect the results of the iteration into this

// string.

// Iterate over the item identifiers of the table.

loops: for (Iterator i = table.getItemIds()

.iterator(); i.hasNext();) {

// Get the current item identifier, which is an

// integer.

int iid = (Integer) i.next();

// Now get the actual item from the table.

Item item = table.getItem(iid);

Object s = new Object();

s = item.getItemProperty("RT- GUI Bezeichnung")

.getValue();

if (s != null) {

bw.write("tempSignals.addSignal('");

bw.write(s.toString());

bw.write("','");

} else {

bw.newLine();

continue loops;

}

s = item.getItemProperty("INCA").getValue();

if (s != null) {

bw.write(s.toString());

bw.write("');");

bw.newLine();

} else {

bw.newLine();

continue loops;

}

try {

if ((double) item.getItemProperty("Max")

.getValue() != 0

|| (double) item.getItemProperty(

"Min").getValue() != 0

|| (double) item.getItemProperty(

"High").getValue() != 0

|| (double) item.getItemProperty(

"Low").getValue() != 0) {

bw.write("tempSignal=tempSignals.getSignal_by_Label('");

bw.write(s.toString());

bw.write("');");

bw.newLine();

bw.write("tempSignal.set('tresholds',{");

s = item.getItemProperty("Min")

.getValue();

bw.write(s.toString());

bw.write(",");

s = item.getItemProperty("Low")

.getValue();

bw.write(s.toString());

bw.write(",");

s = item.getItemProperty("High")

.getValue();

bw.write(s.toString());

bw.write(",");

s = item.getItemProperty("Max")

.getValue();

bw.write(s.toString());

bw.write("});");

bw.newLine();

bw.newLine();

}

} catch (Exception e) {

getApplication()

.getMainWindow()

.showNotification(

"Fehler: Bitte nur Zahlen in die Schwellenbegrenzung schreiben!",

Window.Notification.TYPE_WARNING_MESSAGE);

}

}

bw.close();

} catch (NumberFormatException | IOException e) {

System.out.println(e);

getWindow()

.showNotification(

"Datei konnte nicht gespeichert werden, bitte Eingaben überprüfen");

}

}

}));

getApplication().getMainWindow().addWindow(editorWindow);

if (table.getItem(1).toString().contains("null")) {

table.removeItem(1);

}

}

}