/*
 * Main.fx
 *
 * Created on Nov 29, 2009, 11:30:27 PM
 */
package mdot_gui;

import javafx.scene.Scene;
import javafx.scene.Group;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import mdot_gui.GUIControllerFlagStructure;
import com.sun.javafx.runtime.sequence.Sequence;
import CommonFunctions.debugPrinter;
import mdot.Main;
import mdot_gui.CommonFunctionsFX;
import applications.CarbonControl;
import structures.Constants;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javafx.scene.text.FontWeight;
import client.TMCWebServiceClient;
import edu.wmich.www.cs.mdot.tmc.msg.VMSMessage;
import java.util.Calendar;
import java.applet.AudioClip;
import java.net.URL;
import java.applet.Applet;
import mdot_gui.ChargePointSelection;
import java.lang.UnsupportedOperationException;

/**
 * @author Jamie Lynn
 */
public var screenWidth  ;
public var screenHeight  ;
public var allRects: Sequence;
public var client: TMCWebServiceClient = new TMCWebServiceClient(Main.tmc);
var reportLocationCount: Integer = 0;
var VMSMessageSequence: VMSMessages[];
var args: String[];
var VMSMessage: String = "";
var VMSLastRequestTime: String;
var VMSRequestTimeCounter: Integer = 0;
var VMSReqest: Boolean = true;
var VMSMessageQueueSize: Integer;
var VMSMessageTimeToDisplay: Integer = 0;
var VMSMessageTimeCounter: Integer = 0;
var VMSTimeout: Boolean = false;
var VMSTimeoutTimer: Integer = 0;
public var voipCallStatus: String;
var url: URL = new URL("file:/C:/Documents and Settings/Student/Desktop/Research/Blip.wav");
var clip: AudioClip = Applet.newAudioClip(url);
public var rpm: Double;
public var mph: Double;
public var timeMovingCounter: Integer = 0;
//List of scenes
public def scenelist = [CarContextCourse { }, CarContextFine { }, Applications { }, Sphinx { }, Voip { }];
//This is used for sphinx....order MUST be the same as scenelist
public def scenelistStrings = [CarContextCourse { }.id, CarContextFine { }.id, Applications { }.id, Sphinx { }.id, Voip { }.id];
public var sphinxActiveScene: String = "" on replace {
            SceneManager.sphinxSwapScenes();
        };
var screenRect = Rectangle { width: mdot_gui.Constants.WINDOW_WIDTH;
            height: mdot_gui.Constants.WINDOW_HEIGHT;
            fill: Color.BLACK }
var Button1: GenericButton = ToggleButton {
            id: "btnCallHangup"
            index: 0
            imageButton1: CommonFunctionsFX.getImage("course_lg");
            imageButton2: CommonFunctionsFX.getImage("fine_lg");
            //Start
            onclickButton1Action: function () {
                SceneManager.swapScenes(MainScreen.scenelist[0], 0);
                SceneManager.deactivateSceneButtons();
                Button1.active = true;

            }
            //Stop
            onclickButton2Action: function () {
                SceneManager.swapScenes(MainScreen.scenelist[0], 0);
                SceneManager.deactivateSceneButtons();
                Button1.active = true;

            }
        }
var Button2 = SceneButton {
            id: "btnApps"
            index: 2
            displayimage: CommonFunctionsFX.getImage("app_lg")
        }
var Button3 = SceneButton {
            id: "btnFine"
            index: 3
            displayimage: CommonFunctionsFX.getImage("speak_lg")
        }
var Button4 = SceneButton {
            id: "btnPhone"
            index: 4
            displayimage: CommonFunctionsFX.getImage("phone_lg")
        }
//Dynamic sign area
var Alert1 = AlertImage {
            id: "alertImage1"
        }
var Alert2 = AlertImage {
            id: "alertImage2"
        }
var Alert3 = AlertImage {
            id: "alertImage3"
        }
var Alert4 = AlertImage {
            id: "alertImage4"
        }
//Placeholder for the VMS
var VMSRect: Rectangle;
var VMSArea: Group = Group {
            var rect: Rectangle;
            var txt: Text;
            content: [
                Rectangle {
                    width: mdot_gui.Constants.WINDOW_WIDTH;
                    height: 45
                    layoutY: mdot_gui.Constants.WINDOW_HEIGHT - 45;
                    translateX: 2
                    arcWidth: 15
                    arcHeight: 15
                    fill: null
                    stroke: Color.MEDIUMBLUE
                    strokeWidth: 4
                },
                VMSRect = Rectangle {
                    width: mdot_gui.Constants.WINDOW_WIDTH;
                    height: 45
                    fill: Color.BLACK
                    layoutY: mdot_gui.Constants.WINDOW_HEIGHT - 45;
                    translateX: 2
                    arcWidth: 15
                    arcHeight: 15
                }
                txt = Text {
                    layoutY: mdot_gui.Constants.WINDOW_HEIGHT - 10;
                    layoutX: 10
                    textAlignment: TextAlignment.CENTER;
                    font: Font.font("Arial", FontWeight.BOLD, 38)
                    fill: Color.YELLOW;
                    content: bind VMSMessage
                }
            ]
        }
//Static buttons (Course, Fine, Apps, Voip)
public def SceneButtons: Group = Group {
            content: [VBox {
                    content: [
                        Button1,
                        Button2,
                        Button3,
                        Button4
                    ]
                }
            ]
        }
//Placeholder for alert images
var AlertImages: Group = Group {
            content: [
                VBox {
                    layoutX: screenRect.width - mdot_gui.Constants.BUTTON_SIZE;
                    content: [
                        Alert1,
                        Alert2,
                        Alert3,
                        Alert4
                    ]
                }
            ]
        }
//Place holder where the scenes will the displayed
//ALL scenes are loaded and then made visible/invisible
public var sceneViewer = Group {
            content: [
                scenelist,
                Applications.subscenelist
            ]
        }

public class MainScreen extends Scene, MainScreenJInterface {
        
    override public function transferArgs (arg0 : nativearray of String) : Void {        
        this.args = arg0;
    }


     

     var tl = Timeline {
     repeatCount: Timeline.INDEFINITE
                keyFrames: [
                    KeyFrame {
                        time: 500ms
                        canSkip: true
                        action: function () {

                            //Request list of messages from TMC
                            if (VMSReqest == true and VMSRequestTimeCounter == 0 and VMSTimeout == false) {

                                var date: Calendar = Calendar.getInstance();

                                var VMSlist  ;

                                //Call webservice/Catch timeouts
                                try {
                                    debugPrinter.printLine("CALLING WEBSERVICE!");
                                    VMSlist = client.getVMSList(Main.meString, date);
                                    } catch (Exception) {
                                    debugPrinter.printLine("TMC connection error - VMS.");
                                    VMSTimeout = true;
                                    }

                                //We got a list of messages.
                                if (VMSlist != null) {

                                    //play a sound
                                    clip.play();

                                    for (tmpMsg: VMSMessage in VMSlist) {

                                        //Create a new message
                                        var myMessage: VMSMessages = VMSMessages {
                                                    message: tmpMsg.getMessageTxt();
                                                    time: tmpMsg.getDisplayTime();
                                                }

                                        insert myMessage into VMSMessageSequence;
                                    }
                                }


                                VMSMessageQueueSize = VMSMessageSequence.size();

                                //If we have messages to display, don't request more.
                                if (VMSMessageQueueSize != 0) {
                                    VMSReqest = false;
                                }
                            }

                            if (VMSReqest == false) {
                                if (VMSMessageTimeCounter == VMSMessageTimeToDisplay) {
                                    //time is up, choose another sign
                                    VMSMessageQueueSize = VMSMessageQueueSize - 1;

                                    if (VMSMessageQueueSize < 0) {
                                        VMSMessage = "";
                                        delete  VMSMessageSequence;
                                        VMSMessageQueueSize = 0;
                                        VMSReqest = true;
                                    } else {

                                        //get the message from the list
                                        //display the message in VMS area
                                        var currentMessage: VMSMessages;
                                        currentMessage = VMSMessageSequence[VMSMessageQueueSize];
                                        VMSMessage = currentMessage.message;

                                        //set the time to be displayed
                                        VMSMessageTimeToDisplay = currentMessage.time;

                                        //reset the counter to 0
                                        VMSMessageTimeCounter = 0;
                                    }
                                }
                            }
                            
                           // ENABLE OR DISABLE APPLICATION DEPENDING ON DRIVER RESTRICTION
                           if(args[0].equals("0"))
                            {
                                java.lang.System.out.println("ACCESS STRING : {args[0]}  DISABLE");
                                CommonFunctionsFX.DisableApps(Applications.driverRestriction);
                            }
                            else
                            if(args[0].equals("1"))
                            {
                                java.lang.System.out.println("ACCESS STRING : {args[0]} ENABLE");
                                CommonFunctionsFX.EnableApps(Applications.driverRestriction);
                            }
                            else
                            {
                                CommonFunctionsFX.DisableApps(Applications.driverRestriction);
                            }


                            //If Tracking flag set, send VIN, LAT and LON to TMC
                            if (reportLocationCount == 0 and Main.getMe().GetObjectAsString(Constants.HASH_TRACKING).equals("Yes")) {

                                try {
                                    client.reportVehicleLocation(Main.meString,
                                    Main.getMe().GetObjectAsDouble(Constants.HASH_LATITUDE),
                                    Main.getMe().GetObjectAsDouble(Constants.HASH_LONGITUDE));
                                } catch (Exception) {
                                    java.lang.System.out.println("ERROR - Can't report vehicle location to TMC");
                                }
                            }

                            //If Sphinx flag set, use Sphinx to swap scenes
                            if (Main.getMe().GetObjectAsString(structures.Constants.HASH_SPHINX).equals("YES"))
                                sphinxActiveScene = Main.getMe().GetObjectAsString(structures.Constants.HASH_SPHINX_ACTIVE_SCENE);

                            //Start/Stop Carbon Emissions App
                            if (Main.getMe().GetObjectAsString(structures.Constants.HASH_ENGINE_STATE).equals("ON")) {
                                CarbonControl.StartCarbonEmissionCheck("ON");
                                CommonFunctionsFX.DisableApps(Applications.engineRestriction);
                            } else if (Main.getMe().GetObjectAsString(structures.Constants.HASH_ENGINE_STATE).equals("OFF")) {
                                CarbonControl.StartCarbonEmissionCheck("OFF");
                                CommonFunctionsFX.EnableApps(Applications.engineRestriction);
                            }

                            //Get RPM/MPH for the control panel app
                            rpm = mdot.Main.getMe().GetObjectAsDouble(structures.Constants.HASH_RPM);
                            mph = mdot.Main.getMe().GetObjectAsDouble(structures.Constants.HASH_SPEED);
                            if (rpm == -1)
                                rpm = 0;
                            if (mph == -1)
                                mph = 0;

                            //Check if vehicle is moving
                            if(mph > 0){
                                timeMovingCounter++;
                                if(timeMovingCounter > 5)
                                {
                                    timeMovingCounter = 6;
                                    mdot.Main.getMe().setObjectAsString(structures.Constants.HASH_MOVING, "Yes");
                                }
                            }
                            else{
                                timeMovingCounter = 0;
                                mdot.Main.getMe().removeObject(structures.Constants.HASH_MOVING);
                                }

                            if(mdot.Main.getMe().GetObjectAsString(structures.Constants.HASH_MOVING) != null)
                            {
                               SceneManager.setSceneCourse();
                               CommonFunctionsFX.DisableButtons(Button2, Button3,Button4);
                            }
                            else
                            {
                              CommonFunctionsFX.EnableButtons(Button2, Button3,Button4);
                            }

                            //Check call status
                            voipCallStatus = local.ua.UACallSetup.getCallStatus();

                            //Blink squares
                            var locationsToBlink: Sequence = CommonFunctionsFX.searchContextHashTable(SceneManager.getActiveScene());

                            if (locationsToBlink.size != 0) {
                                animation.blink(locationsToBlink);
                            } else {
                                animation.reset(allRects);
                            }

                            //Insert Signs into Alert Areas
                            var seqSigns: Sequence = ImageSelectionCriteria.ReturnSigns();
                            Alert1.imageArea.image = CommonFunctionsFX.getImage(seqSigns[0] as String);
                            Alert2.imageArea.image = CommonFunctionsFX.getImage(seqSigns[1] as String);
                            Alert3.imageArea.image = CommonFunctionsFX.getImage(seqSigns[2] as String);
                            Alert4.imageArea.image = CommonFunctionsFX.getImage(seqSigns[3] as String);

                            ChargePointSelection.CheckChargePoints();

                            //update counters
                            reportLocationCount = ((reportLocationCount + 1) mod 5);
                            VMSMessageTimeCounter = (VMSMessageTimeCounter + 1) mod (VMSMessageTimeToDisplay + 1);
                            VMSRequestTimeCounter = ((VMSRequestTimeCounter + 1) mod 30);

                            //Wait 10 rotations before trying the TMC again
                            if (VMSTimeout == true) {
                                VMSTimeoutTimer = (VMSTimeoutTimer + 1) mod 10;
                                if (VMSTimeoutTimer == 0)
                                    VMSTimeout = false;
                            }
                        }
                    }
                    KeyFrame {
                        time: 1s
                        action: function () {
                            animation.reset(allRects);

                            //Get RPM/MPH for the control panel app
                            rpm = mdot.Main.getMe().GetObjectAsDouble(structures.Constants.HASH_RPM);
                            mph = mdot.Main.getMe().GetObjectAsDouble(structures.Constants.HASH_SPEED);
                            if (rpm == -1)
                                rpm = 0;
                            if (mph == -1)
                                mph = 0;
                        }
                    }
                ]
            }
    override var content = [
                screenRect,
                SceneButtons, //Static Buttons on LEFT
                sceneViewer, //Scene viewing area
                AlertImages, //Place holder for alerts
                VMSArea //Placeholder for VMS

            ];
    //set the background color

    init {

        screenWidth = this.width as Integer;
        screenHeight = this.height as Integer;
        allRects = CommonFunctionsFX.getAllRects();

        java.lang.System.out.println("WIDTH: {screenWidth} HEIGHT: {screenHeight}");

        fill = Color.BLACK;
        SceneManager.setActiveButton(0);
        tl.play();

    }

}
/*C = car location
|8|1|2|
-------
|7|C|3|
-------
|6|5|4|
 */
//Flags for COURSE Context
public var courseRect1 = GUIControllerFlagStructure { };
public var courseRect2 = GUIControllerFlagStructure { };
public var courseRect3 = GUIControllerFlagStructure { };
public var courseRect4 = GUIControllerFlagStructure { };
public var courseRect5 = GUIControllerFlagStructure { };
public var courseRect6 = GUIControllerFlagStructure { };
public var courseRect7 = GUIControllerFlagStructure { };
public var courseRect8 = GUIControllerFlagStructure { };
//Flags for FINE Context
public var fineRect1 = GUIControllerFlagStructure { };
public var fineRect2 = GUIControllerFlagStructure { };
public var fineRect3 = GUIControllerFlagStructure { };
public var fineRect4 = GUIControllerFlagStructure { };
public var fineRect5 = GUIControllerFlagStructure { };
public var fineRect6 = GUIControllerFlagStructure { };
public var fineRect7 = GUIControllerFlagStructure { };
public var fineRect8 = GUIControllerFlagStructure { };
public var fineRect9 = GUIControllerFlagStructure { };
public var fineRect10 = GUIControllerFlagStructure { };
public var fineRect11 = GUIControllerFlagStructure { };
public var fineRect12 = GUIControllerFlagStructure { };
public var fineRect13 = GUIControllerFlagStructure { };
public var fineRect14 = GUIControllerFlagStructure { };
public var fineRect15 = GUIControllerFlagStructure { };
public var fineRect16 = GUIControllerFlagStructure { };
public var fineRect17 = GUIControllerFlagStructure { };
public var fineRect18 = GUIControllerFlagStructure { };
public var fineRect19 = GUIControllerFlagStructure { };
public var fineRect20 = GUIControllerFlagStructure { };
public var fineRect21 = GUIControllerFlagStructure { };
public var fineRect22 = GUIControllerFlagStructure { };
public var fineRect23 = GUIControllerFlagStructure { };
public var fineRect24 = GUIControllerFlagStructure { };





public class VMSMessages {

    var message: String;
    var time: Integer;
}
