/*************************************************************************
*
* ADOBE CONFIDENTIAL
* ___________________
*
*  Copyright 2008 Adobe Systems Incorporated
*  All Rights Reserved.
*
* NOTICE:  All information contained herein is, and remains
* the property of Adobe Systems Incorporated and its suppliers,
* if any.  The intellectual and technical concepts contained
* herein are proprietary to Adobe Systems Incorporated and its
* suppliers and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Adobe Systems Incorporated.
**************************************************************************/

include "CallLegTab.as"
include "serverTab.as"
include "consoleTab.as"

// ActionScript file
import flash.events.Event;
import flash.events.FocusEvent;
import flash.net.NetConnection;
import flash.net.SharedObject;

import mx.core.Application;


// 
[Bindable] private var refreshRate_index:int = 1;
[Bindable] private var refreshRate_data:Array = new Array(1, 2, 5, 10, 15);

public const DEFAULT_USERNAME  : String = "admin";
public const DEFAULT_SERVICE   : String = "telephony_control";
public const DEFAULT_SERVER    : String = "rtmp://localhost/control";
public const DEFAULT_CONNECT   : Boolean = false;
public const DEFAULT_PASSWORD  : String = "";

// Global variables that are phone specific.
public var state:String = null;
public var phoneID:String = null;
private var nc:NetConnection;
private var sharedObject:SharedObject; 
private var result:Object = new Object();
private var isPhoneConnected:Boolean = false;

private var myTimer:Timer = new Timer(1000, 0);




/*
* Login processs 
*
*
*/
// Default values for Login screen 
public function customUIFunction(evt:FocusEvent):void{
    if(evt.type == FocusEvent.FOCUS_IN){
        switch (evt.currentTarget.id){
            case "servicename":
                            if(Login_ServiceName.text == DEFAULT_SERVICE) Login_ServiceName.text = ""; break;
            case "url":
                            if(Login_URL.text == DEFAULT_SERVER) Login_URL.text = ""; break;
            case "username":
                            if(Login_UserName.text == DEFAULT_USERNAME) Login_UserName.text = ""; break;
            case "password":
                            if(Login_Password.text == DEFAULT_PASSWORD) Login_Password.text = ""; break;
        }
    }
    else if(evt.type == FocusEvent.FOCUS_OUT){
        switch (evt.currentTarget.id){
            case "servicename":
                            if(Login_ServiceName.text == "") Login_ServiceName.text = DEFAULT_SERVICE; break;
            case "url":
                            if(Login_URL.text == "") Login_URL.text = DEFAULT_SERVER; break;
            case "username":
                            if(Login_UserName.text == "") Login_UserName.text = DEFAULT_USERNAME; break;
            case "password":
                            if(Login_Password.text == "") Login_Password.text = DEFAULT_PASSWORD; break;
        }
    }
}
// Add event listernes for Login screen buttons
public function addListeners():void{
    Login_ServiceName.addEventListener(FocusEvent.FOCUS_IN,customUIFunction);
    Login_ServiceName.addEventListener(FocusEvent.FOCUS_OUT,customUIFunction);

    Login_URL.addEventListener(FocusEvent.FOCUS_IN,customUIFunction);
    Login_URL.addEventListener(FocusEvent.FOCUS_OUT,customUIFunction);

    Login_UserName.addEventListener(FocusEvent.FOCUS_IN,customUIFunction);
    Login_UserName.addEventListener(FocusEvent.FOCUS_OUT,customUIFunction);
    
    Login_Password.addEventListener(FocusEvent.FOCUS_IN,customUIFunction);
    Login_Password.addEventListener(FocusEvent.FOCUS_OUT,customUIFunction);
    
    
}
// Look at local shared object for login screen settings.
public function getSharedObject():void
{
    sharedObject = SharedObject.getLocal("mydata");
    if(sharedObject)
    {
        Login_ServiceName.text    = (sharedObject.data.servicename) ? sharedObject.data.servicename : DEFAULT_SERVICE;
        Login_URL.text         = (sharedObject.data.url)? sharedObject.data.url : DEFAULT_SERVER;
        Login_UserName.text = (sharedObject.data.userName) ? sharedObject.data.userName : DEFAULT_USERNAME;
        Login_Password.text = (sharedObject.data.password) ? sharedObject.data.password : DEFAULT_PASSWORD;
        Login_RememberSettingsBox.selected    = (sharedObject.data.connect) ? sharedObject.data.connect : DEFAULT_CONNECT;
    }
}
// set local shared object for storing login screen settings for next session.
public function setSharedObject(flag:Boolean):void
{
    if(flag){
        sharedObject.data.servicename    = Login_ServiceName.text;
        sharedObject.data.url             = Login_URL.text;
        sharedObject.data.userName         = Login_UserName.text;
        sharedObject.data.password         = Login_Password.text;
        sharedObject.data.connect        = Login_RememberSettingsBox.selected;
        sharedObject.flush();
    }
    else
    {
        sharedObject.clear();
    }
}
// Implementation of remember setting checkbox handler.
public function RememberSettings(evt:Event):void{
    if(Login_RememberSettingsBox.selected){
        setSharedObject(true);
    }else{
        setSharedObject(false);
    }
}

// onInit is the start point of application.
public function onInit():void{
    //Initialize Netconnection object, streams utility objects & event handlers.
    
    getSharedObject();
    addListeners();
    nc = new NetConnection();
    nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
    nc.client = new Object();
    nc.client.onResponse = onResponse;
    //nc.client.onLeg = onLeg;
    //nc.client.onLegMessage = onLegMessage;
    //nc.client.onLegUpdate = onLegUpdate;
    //myTimer.addEventListener(TimerEvent.TIMER, EnterFrameHandler);
    Login_RememberSettingsBox.addEventListener(Event.CHANGE, RememberSettings);

    if(Login_RememberSettingsBox.selected){
        // Do auto login
        onSignIn();
    }
}

private function onSignIn():void{
    if(Login_RememberSettingsBox.selected){
        setSharedObject(true);
    }else{
        setSharedObject(false);
    }
    if(Login_LoginBtn.label == "Connect"){
        myTrace("Connecting...");
        Login_LoginBtn.label = "Cancel";
        nc.connect(Login_URL.text,Login_UserName.text,Login_Password.text);
    }else if(Login_LoginBtn.label == "Cancel"){
        stopConnecting();
    }
}

private function myTrace(str:String):void{
    trace(str);
}


// button handler
private function stopConnecting():void{
    exitAdmin();
    Login_LoginBtn.label = "Connect";
    myTrace("...Cancelled.");
    return;
}

// Method to indicate SSAS app to request FMG service
private function onService():void{
    nc.call("requestService", null, Login_ServiceName.text);
}



// RTMP Connection is now established, start Admin.
private function initAdmin():void{
    //myTimer.start();
    onService();
    initCallLegsTab();    
    // UI related initial settings
    //cleanUp();
}

private function onSignout():void{
    exitAdmin();
}
private function goToCallLegsTab():void{
    initCallLegsTab();
}
private function goToConsoleTab():void{
    initConsoleTab()
}
private function goToServerStatusTab():void{
    initServerTab();
}

// Cleanup connection and exit phone.
private function exitAdmin():void{
    Application.application.currentState = "Login";
    nc.close();
}


// Netconnection status event handler
private function netStatusHandler(event:NetStatusEvent):void{
    myTrace(event.info.code);
    if(event.info.code  == "NetConnection.Connect.Success"){
        login_error_box.text= "";        
        initAdmin();
    }else if(event.info.code  == "NetConnection.Connect.Closed"){
        exitAdmin();
        Login_LoginBtn.label = "Connect";
        SoundMixer.stopAll();
    }else{        
        exitAdmin();
        myTrace("Cannot connect to server. Please review your settings");
        login_error_box.text= "Cannot connect to server. Please review your settings.";
        Login_LoginBtn.label = "Connect";
        if(event.info.code  == "NetConnection.Connect.Rejected"){
            myTrace("Conection rejected; Invalid username/Password");
            login_error_box.text= "Conection rejected; Invalid username/Password Or wrong URL.";
        }else if( event.info.code  == "NetConnection.Connect.failed"){
            myTrace("Connection failed; Please check the URL and FMS server side App");
            login_error_box.text= "Connection failed; Please check the URL";
        }else{
            // do nothing
        }
    }
}



public function onResponse (info:Object):void{
    myTrace("inside on Response");
    myTrace("\n Type:"+info.type);
    myTrace("\t Status:"+info.status);
    myTrace("\t refID: "+ info.refID);
    myTrace("\t\n LegID: "+ info.legID);
    if(info.type == "control.response.command"){
        info.data.reverse();
        for( var i:String in info.data){
            myTrace("\t\n>>" + info.data[i]);
        }
    }
    
    switch (Application.application.currentState ){
        
        case "Call Legs":
            onResultCallLegsTab(info);
            break;
            
        case "Console":
            onResultConsoleTab(info);
            break;
        
        case "Server_Status":
            onResultServerStatusTab(info);
            break;
        default:
            // do nothing
            break;
        
             
    }
}


private function onEvent(info:Object):void{
    myTrace("\n Event Type:"+info.type);
    myTrace("\t LegID: "+ info.legID);
    if(info.type == "control.event.legcreated"){
        myTrace("\t\n legType:"+info.legType);
        myTrace("\t\t callerName:"+info.callerName);
        myTrace("\t\n callerNum:"+info.callerNum);
        myTrace("\t\t destNum:"+info.destNum);
    }
    if( info.type == "control.event.app"){
        myTrace("\t\n appName :"+info.appName) ;
        myTrace("\t\n data:"+info.data);
    }
    myTrace("\n>");
}


private function onCreateLeg(arg1:String, arg2:String, arg3:String):void{
    trace("in onCreateLeg " );
    nc.call("createLeg", null, arg1, arg2);
}

private function onHangupLeg(arg1:String, arg2:String, arg3:String):void{
    trace("in onHangupLeg " );
    nc.call("hangupLeg", null, arg1, arg2);
}
private function onMoveLeg(arg1:String, arg2:String, arg3:String):void{
    trace("in onMoveLeg " );
    nc.call("moveLeg", null, arg1, arg2);
}
private function onExecuteCommand(arg1:String, arg2:String, arg3:String):void{
    trace("in onExecuteCommand");
    nc.call("executeCommand", null, arg1, arg2,arg3);
}

private function onServiceStop():void{
    nc.call("stopService", null);
}

private function onRequest ():void{
    trace("in onRequest");
    /*
    if(executeCommand_RadioBtn.selected){
        
        onExecuteCommand( (arg1_box.text == "")? null:arg1_box.text ,
                        (arg2_box.text == "")? null:arg2_box.text ,
                        (arg3_box.text == "")? null:arg3_box.text );
    }
    if(createLeg_RadioBtn.selected){
        
        onCreateLeg( (arg1_box.text == "")? null:arg1_box.text ,
                        (arg2_box.text == "")? null:arg2_box.text ,
                        (arg3_box.text == "")? null:arg3_box.text );
    }
    if(hangupLeg_RadioBtn.selected){
        
        onHangupLeg( (arg1_box.text == "")? null:arg1_box.text ,
                        (arg2_box.text == "")? null:arg2_box.text ,
                        (arg3_box.text == "")? null:arg3_box.text );
    }
    if(moveLeg_RadioBtn.selected){
        
        onMoveLeg( (arg1_box.text == "")? null:arg1_box.text ,
                        (arg2_box.text == "")? null:arg2_box.text ,
                        (arg3_box.text == "")? null:arg3_box.text );
    }
    */
}

private function onRefreshRateChange():void{
    // update refresh rate
    refreshTime = new int (refreshCombo_serverTab.selectedLabel);
        
}