/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.machinist.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RichTextArea;
import com.google.gwt.user.client.ui.TextArea;
import org.machinist.client.hardware.GPSservice;
import org.machinist.client.hardware.GPSserviceAsync;

import org.gwtopenmaps.openlayers.client.Bounds;
import org.gwtopenmaps.openlayers.client.Icon;
import org.gwtopenmaps.openlayers.client.event.EventObject;
import org.gwtopenmaps.openlayers.client.util.JObjectArray;
import org.gwtopenmaps.openlayers.client.util.JSObject;
import org.gwtopenmaps.openlayers.client.LonLat;
import org.gwtopenmaps.openlayers.client.Map;
import org.gwtopenmaps.openlayers.client.MapOptions;
import org.gwtopenmaps.openlayers.client.MapWidget;
import org.gwtopenmaps.openlayers.client.Marker;
import org.gwtopenmaps.openlayers.client.Pixel;
import org.gwtopenmaps.openlayers.client.Size;
import org.gwtopenmaps.openlayers.client.control.PanZoomBar;
import org.gwtopenmaps.openlayers.client.control.MouseToolbar;
import org.gwtopenmaps.openlayers.client.control.LayerSwitcher;
import org.gwtopenmaps.openlayers.client.event.EventHandler;
import org.gwtopenmaps.openlayers.client.layer.Layer;
import org.gwtopenmaps.openlayers.client.layer.Markers;
import org.gwtopenmaps.openlayers.client.layer.WMS;
import org.gwtopenmaps.openlayers.client.layer.WMSParams;
import org.gwtopenmaps.openlayers.client.popup.AnchoredBubble;
import org.gwtopenmaps.openlayers.client.popup.Popup;
import org.gwtopenmaps.openlayers.client.event.MapClickListener;

import com.google.gwt.user.client.ui.DockPanel;

/**
 * Main entry point.
 *
 * @author BURKAY
 * @author cagr1
 */
public class MainEntryPoint implements EntryPoint {

    /**
     * Creates a new instance of MainEntryPoint
     */
    Marker marker, marker2, marker3;
    MapWidget mapWidget;
    Map map;
    WMS wmsLayer;
    Markers markers;
    Label GpsStream = new Label();
    Label trainId = new Label();
    Label speed = new Label();
    Label longitude = new Label();
    Label latitude = new Label();
    Label time = new Label();
    Label xang = new Label();
    Label yang = new Label();
    Label train2Id = new Label();
    Label speed2 = new Label();
    Label longitude2 = new Label();
    Label latitude2 = new Label();
    Label time2 = new Label();
    Label xang2 = new Label();
    Label yang2 = new Label();
    Label train3Id = new Label();
    Label speed3 = new Label();
    Label longitude3 = new Label();
    Label latitude3 = new Label();
    Label time3 = new Label();
    Label xang3 = new Label();
    Label yang3 = new Label();
    int whichTrain = 1;
    FlexTable flexTable = new FlexTable();

    public MainEntryPoint() {
    }

    public static GPSserviceAsync getService() {
        // Create the client proxy. Note that although you are creating the
        // service interface proper, you cast the result to the asynchronous
        // version of the interface. The cast is always safe because the
        // generated proxy implements the asynchronous interface automatically.

        return GWT.create(GPSservice.class);
    }
    /** 
     * The entry point method, called automatically by loading a module
     * that declares an implementing class as an entry-point
     */
    String[] fields = new String[21];

    public void onModuleLoad() {

        String IPAddress = "localhost";

        // map options
        MapOptions mapOptions = new MapOptions();
        mapOptions.setControls(new JObjectArray(new JSObject[]{}));
        mapOptions.setNumZoomLevels(13);
        mapOptions.setProjection("EPSG:4326");

        // map widget and map objects
        mapWidget = new MapWidget("650px", "400px", mapOptions);
        map = mapWidget.getMap();
        markers = new Markers("Trains");

        // WMS map layers
        WMSParams wmsParams = new WMSParams();
        wmsParams.setFormat("image/png");
        wmsParams.setLayers("trenler:tu,railways,metropolitan_coordinates,province_coordinates");
        wmsParams.setStyles("");
        wmsParams.setMaxExtent(new Bounds(28.0, 36.0, 43.0, 42.0));
        wmsLayer = new WMS("Whole Map", "http://" + IPAddress + ":8085/geoserver/wms", wmsParams);
        map.addLayers(new Layer[]{wmsLayer, markers});

        wmsParams.setLayers("trenler:tu,railways");
        WMS wmsL = new WMS("Base & Railways", "http://" + IPAddress + ":8085/geoserver/wms", wmsParams);
        map.addLayer(wmsL);

        wmsParams.setLayers("trenler:tu");
        wmsL = new WMS("Only Base", "http://" + IPAddress + ":8085/geoserver/wms", wmsParams);
        map.addLayer(wmsL);

        wmsParams.setLayers("trenler:railways");
        wmsL = new WMS("Only Railways", "http://" + IPAddress + ":8085/geoserver/wms", wmsParams);
        map.addLayer(wmsL);

        // map controls
        map.addControl(new PanZoomBar());
        map.addControl(new MouseToolbar());
        map.addControl(new LayerSwitcher());
/*
        MapClickListener mapClickListener = new MapClickListener() {

            public void onClick(MapClickEvent eventObject) {
                LonLat lonlat = eventObject.getLonLat();
                if (((int) lonlat.lat()) == (int) Integer.parseInt(latitude.getText())
                        && ((int) lonlat.lon()) == (int) Integer.parseInt(longitude.getText())) {
                    whichTrain = 1;
                } else if (((int) lonlat.lat()) == (int) Integer.parseInt(latitude2.getText())
                        && ((int) lonlat.lon()) == (int) Integer.parseInt(longitude2.getText())) {
                    whichTrain = 2;
                } else if (((int) lonlat.lat()) == (int) Integer.parseInt(latitude3.getText())
                        && ((int) lonlat.lon()) == (int) Integer.parseInt(longitude3.getText())) {
                    whichTrain = 3;
                }
            }
        };

        map.addMapClickListener(mapClickListener);
*/
        LonLat center = new LonLat(26.56, 41.69);
        map.setCenter(new LonLat(35.5, 39.0), 6);

        // add marker
        Size size = new Size(22, 22);
        Pixel offset = new Pixel((int) -(size.getHeight() / 2), (int) -size.getHeight());
        final Icon icon = new Icon("http://www.ceng.metu.edu.tr/~e1502103/img/marker.png", size, offset);
        final Icon icon2 = new Icon("http://www.ceng.metu.edu.tr/~e1502103/img/marker.png", size, offset);
        final Icon icon3 = new Icon("http://www.ceng.metu.edu.tr/~e1502103/img/marker.png", size, offset);
        marker = new Marker(new LonLat(0, 0), icon);
        markers.addMarker(marker);
        marker2 = new Marker(new LonLat(0, 1), icon2);
        markers.addMarker(marker2);
        marker3 = new Marker(new LonLat(0, 2), icon3);
        markers.addMarker(marker3);

        Timer timer = new Timer() {

            public void run() {
                //create an async callback to handle the result:
                AsyncCallback callback = new AsyncCallback() {

                    public void onFailure(Throwable arg0) {
                        //display error text if we can't get the quote:
                        GpsStream.setText("Failed to get stream or server is stopped.");
                    }

                    public void onSuccess(Object result) {
                        //display the retrieved quote in the label:
                        GpsStream.setText((String) result);
                        fields = GpsStream.getText().split("\\|");
                        trainId.setText(fields[0].trim());
                        speed.setText(fields[1].trim());
                        longitude.setText(fields[2].trim());
                        latitude.setText(fields[3].trim());
                        time.setText(fields[4].trim());
                        xang.setText(fields[5].trim());
                        yang.setText(fields[6].trim());

                        train2Id.setText(fields[7].trim());
                        speed2.setText(fields[8].trim());
                        longitude2.setText(fields[9].trim());
                        latitude2.setText(fields[10].trim());
                        time2.setText(fields[11].trim());
                        
                        train3Id.setText(fields[12].trim());
                        speed3.setText(fields[13].trim());
                        longitude3.setText(fields[14].trim());
                        latitude3.setText(fields[15].trim());
                        time3.setText(fields[16].trim());
                        /*
                        xang2.setText(fields[17].trim());
                        yang2.setText(fields[18].trim());
                        xang3.setText(fields[19].trim());
                        yang3.setText(fields[20].trim());
*/

                        LonLat lola1 = new LonLat(Double.parseDouble(longitude.getText()), Double.parseDouble(latitude.getText()));
                        markers.removeMarker(marker);
                        marker = new Marker(lola1, icon);
                        markers.addMarker(marker);
                        LonLat lola2 = new LonLat(Double.parseDouble(longitude2.getText()), Double.parseDouble(latitude2.getText()));
                        markers.removeMarker(marker2);
                        marker2 = new Marker(lola2, icon2);
                        markers.addMarker(marker2);
                        LonLat lola3 = new LonLat(Double.parseDouble(longitude3.getText()), Double.parseDouble(latitude3.getText()));
                        markers.removeMarker(marker3);
                        marker3 = new Marker(lola3, icon3);
                        markers.addMarker(marker3);

                        markers.redraw(true);

                    }
                };
                getService().myMethod(callback);
            }
        };

        timer.scheduleRepeating(800);
        /*RootPanel.get().add(GpsStream);
        RootPanel.get().add(trainId);
        RootPanel.get().add(speed);
        RootPanel.get().add(longitude);
        RootPanel.get().add(latitude);
        RootPanel.get().add(time);
        RootPanel.get().add(xang);
        RootPanel.get().add(yang);*/



        flexTable.setText(0, 0, "Tren Numarası");
        flexTable.setText(1, 0, "Hızınız");
        flexTable.setText(2, 0, "Konumunuz");
        flexTable.setText(3, 0, " ");
        flexTable.setText(4, 0, "Yatay Açı");
        flexTable.setText(5, 0, " ");
        flexTable.setText(6, 0, "Saat");

        /*
        if (whichTrain == 1) {
            flexTable.setWidget(0, 1, trainId);
            flexTable.setWidget(1, 1, speed);
            flexTable.setWidget(2, 1, longitude);
            flexTable.setWidget(3, 1, latitude);
            flexTable.setWidget(4, 1, xang);
            flexTable.setWidget(5, 1, yang);
            flexTable.setWidget(6, 1, time);
        } else if (whichTrain == 2) {
            flexTable.setWidget(0, 1, train2Id);
            flexTable.setWidget(1, 1, speed2);
            flexTable.setWidget(2, 1, longitude2);
            flexTable.setWidget(3, 1, latitude2);
            flexTable.setWidget(4, 1, xang2);
            flexTable.setWidget(5, 1, yang2);
            flexTable.setWidget(6, 1, time2);
        } else if (whichTrain == 3) {
            flexTable.setWidget(0, 1, train3Id);
            flexTable.setWidget(1, 1, speed3);
            flexTable.setWidget(2, 1, longitude3);
            flexTable.setWidget(3, 1, latitude3);
            flexTable.setWidget(4, 1, xang3);
            flexTable.setWidget(5, 1, yang3);
            flexTable.setWidget(6, 1, time3);
        } else {

        */
            flexTable.setWidget(0, 1, trainId);
            flexTable.setWidget(1, 1, speed);
            flexTable.setWidget(2, 1, longitude);
            flexTable.setWidget(3, 1, latitude);
            flexTable.setWidget(4, 1, xang);
            flexTable.setWidget(5, 1, yang);
            flexTable.setWidget(6, 1, time);
        //}

        flexTable.setBorderWidth(1);
        flexTable.setCellPadding(2);
        flexTable.setCellSpacing(2);

        flexTable.setPixelSize(300, 400);


        RootPanel.get("stream").add(flexTable);

        DockPanel dockPanel = new DockPanel();
        dockPanel.add(mapWidget, DockPanel.CENTER);
        dockPanel.setBorderWidth(2);
        RootPanel.get("map").add(dockPanel);
    }
}
