
var cert_label_done_button = $L("Done");
var cert_label_connecting_button = $L("Connecting...");

JoincertAssistant = Class.create({
   
    selectedCert: '',
    
    initialize: function(sceneAssistant, profile){
        Mojo.Log.info("Joincert initialize " + NetworkList.printProfile(profile));
        
        this.certList = new Array();
        
        this.sceneAssistant = sceneAssistant;
        this.controller = this.sceneAssistant.controller;
        
        if (profile) {
            this.joinProfile = profile;
        }		
    },
    
    setup: function(widget){
        this.widget = widget;
        this.titleElement = this.controller.get('cert_joinTitle');
        this.statusMessage = this.controller.get('cert_statusMessage');
		this.warningIcon = this.controller.get('cert_warningIcon');
		this.warningIcon.hide();
        
        if(this.titleElement)
            this.titleElement.innerHTML = this.titleElement.innerHTML + " " + this.joinProfile.ssid.escapeHTML();
		
		this.joinButtonModel = {buttonLabel: cert_label_done_button};
		this.joinButton = this.controller.get('cert_joinButton');		
        this.controller.setupWidget('cert_joinButton', {type:Mojo.Widget.activityButton}, this.joinButtonModel);
		Mojo.Event.listen(this.joinButton,'mojo-tap', this.joinNetwork.bind(this))
        
        this.certSelector = this.controller.get('certSelector');
        this.certSelector.observe('mojo-property-change', this.selectorChanged.bindAsEventListener(this));
        this.certModel = {
            value: this.selectedCert,
			disabled: true
        };
        
        this.controller.setupWidget('certSelector', {
			choices: this.certList
        }, this.certModel);
		
        var request = this.controller.serviceRequest('palm://com.palm.certificatemanager', {
            method: 'listcertificates',
            onSuccess: function(response){
                Mojo.Log.info("joincert response " + Object.toJSON(response));
                this.certList.clear();
                 
                $A(response.userCertificateStore).each(function(a){
                    Mojo.Log.info("joincert response " + Object.toJSON(a));
					var itemLabel = a.commonname ? a.commonname : a.organization                    
                    var item = {
                        label: itemLabel ? itemLabel : "",
                        expiredate: a.expiredate,
                        certificateFilename: a.certificateFilename,
                        value: a.certificateId
                    };
                    this.certList.push(item);
                }.bind(this));
                
				Mojo.Log.info("joincert length ", this.certList.length );
				if (this.certList.length == 0) {
					var item = {
                        label: $L("None"),
						value: ""
                    };
                    this.certList.push(item);
					this.certModel.disabled = true;
					
					this.joinButtonModel.disabled = true;
					this.controller.modelChanged(this.joinButtonModel);
				} else {
					this.certModel.disabled = false;
					this.joinButtonModel.disabled = false;
					this.controller.modelChanged(this.joinButtonModel);
				}
				
				if (this.certList.first().value) {
					this.certModel.value = this.selectedCert = this.certList.first().value;
				}
				
                this.controller.modelChanged(this.certModel, this);
            }.bind(this),
            onFailure: function(response){
            	Mojo.Log.info("joincert get list failure" + Object.toJSON(response));
            }.bind(this)
        });     
		
        var appMenuModel = {
            visible: true,
            items: [Mojo.Menu.editItem, Mojo.Menu.helpItem]
        };
        this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems: true}, appMenuModel);

    },
    
    
    selectorChanged: function(event){
        this.selectedCert = event.value;
        Mojo.Log.info("selectorChanged " + this.selectedCert);
    },
	
	getPath: function(certificateId) {
		var item = {};
		this.certList.each(function(a){
			if(a.value == certificateId)
			{
				Mojo.Log.info("getpath: " + certificateId + " " + Object.toJSON(a));
				item = a; 
			}
		}.bind(this));
		
		return item;
	},
    
	
    joinNetwork: function(event){
		event.stop();
		Mojo.Log.info("joinNetwork", this.selectedCert);
		if (this.selectedCert && (this.selectedCert != "")) {
			this.clearStatusMessage();

			this.setButtonState(true);
			
	        var ssidPattern = /[a-zA-Z0-9]+/;

            var profile = this.joinProfile;
            profile.security.enterpriseSecurity.clientCertificatePath = this.getPath(this.selectedCert).certificateFilename;
            
            this.joinProfile = profile;
            NetworkList.connect(this.controller, profile, this.handleConnect, this.handleConnectFailure.bind(this, profile));
        }
        else {
        }
    },
    
	setButtonState: function(state) {
		if (state) {
			this.joinButtonModel.buttonLabel = cert_label_connecting_button;
//			this.joinButtonModel.disabled = true;
			this.controller.modelChanged(this.joinButtonModel);		
			this.joinButton.mojo.activate();
			
			this.certModel.disabled = true;
			this.controller.modelChanged(this.certModel);
		}
		else {
			this.joinButtonModel.buttonLabel = cert_label_done_button;
//			this.joinButtonModel.disabled = false;
			this.controller.modelChanged(this.joinButtonModel);
			this.joinButton.mojo.deactivate();
			
			this.certModel.disabled = false;
			this.controller.modelChanged(this.certModel);

		}
	},

    handleStatusNotification: function(response){
        Mojo.Log.info("Joincert handleStatus " + Object.toJSON(response));
		
		if (response.status == 'serviceDisabled') {
			this.widget.mojo.close();
		} else if (this.joinProfile && response.networkInfo) {
            if (this.joinProfile.ssid == response.networkInfo.ssid) {
                switch (response.status) {
                    case 'connectionStateChanged':
                        var item = response.networkInfo;
                        switch (item.connectState) {
                            case 'associated':
                                if (item.lastConnectError == undefined) {
                                    this.widget.mojo.close();
                                }
                                else {
                                    this.updateStatusMessage(item.lastConnectError);
                                }
								
								this.setButtonState(false);								
                                break;
                            case 'associationFailed':
                                this.updateStatusMessage(item.lastConnectError);
								
								this.setButtonState(false);								
                                break;
                        }
                        ;
                        break;
                };
            }
        }
    },
    
    updateStatusMessage: function(message){
    
        var l = label_status_message_unknown;
        if (message != undefined) {
            var label = "label_status_message_" + message.toLowerCase();
            try {
                l = eval(label);
            } 
            catch (err) {
                l = label_status_message_unknown;
            }
        }
        this.statusMessage.innerHTML = l;
		this.warningIcon.show();
    },
    
    clearStatusMessage: function(){
        this.statusMessage.innerHTML = "";
		this.warningIcon.hide();               
    },

    getStatusResponseFailed: function(response){
        Mojo.Log.warn("joincert getStatusFailed " + Object.toJSON(response));
    },
    
    cleanup: function(){
        Mojo.Log.info("joincert cleanup ");
    },
    
    handleConnect: function(response){
        Mojo.Log.info("joincert Trying to connect");
    },
    
    handleConnectFailure: function(item, response){
        Mojo.Log.warn("joincert connect failed: " + Object.toJSON(response));
        this.updateStatusMessage(response.errorText);
    },
    
    activate: function(){
        Mojo.Log.info("joincert activate");
        this.subscribeHandle = NetworkList.subscribe(this.controller, true, this.handleStatusNotification.bind(this), this.getStatusResponseFailed.bind(this));        
    },
    
    deactivate: function(){
        Mojo.Log.info("joincert deactivate");
		if(this.subscribeHandle) {
	        this.subscribeHandle.cancel();
	    }

    },

});
