var label_valid_cert = $L("Valid certificate");
var lable_invalid_cert = $L("Invalid certificate");


ListAssistant = Class.create({

	initialize: function(target){
		Mojo.Log.info("cert init " + Object.toJSON(target));
		if (target.target) {
			Mojo.Log.info("cert init target");
			this.params = target;
		}
	},
	
	certificateList: new Array(),
	
	setup: function(){
		Mojo.Log.info("cert setup ");
		
		this.certificateListElement = this.controller.get('certificateList');
		this.emptyText = this.controller.get('certificateListEmptyText');
		
		this.certificateListModel = {
			items: this.certificateList,
		};
		
		this.template = {
			itemTemplate: 'list/certlist-item',
		};
		
		this.controller.setupWidget('certificateList', this.template, this.certificateListModel);
		this.certificateListElement.observe(Mojo.Event.listTap, this.listSelectionHandler.bindAsEventListener(this));
		this.emptyText.hide();
		
		this.cmdMenuModel = {
			items: [{
				iconPath: 'images/cert_menu_button.png',
				command: 'addItem'
			}]
		};
		
		this.controller.setupWidget(Mojo.Menu.commandMenu, undefined, this.cmdMenuModel);
		
        var appMenuModel = {
            visible: true,
            items: [Mojo.Menu.editItem, Mojo.Menu.helpItem]
        };
        this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems: true}, appMenuModel);

		if (this.params) {
			Mojo.Log.info("cert init params " + Object.toJSON(this.params));
			this.getDetails({
				'certificateFilename': this.params.target.sub('file://', '')
			});
		}
	},
	
	handleCommand: function(event){
		if (event.type == Mojo.Event.command) {
			if (event.command == 'addItem') {
				var params = {
					actionType: 'attach',
					kinds: ['file'],
					defaultKind: 'file',
					extensions: ['pem', 'p12', 'der', 'cer', 'pfx', 'crt'], //'crl'
					onSelect: function(file){
						Mojo.Log.info("cert open ", file.fullPath);
						this.fileFullPath = file.fullPath;
						this.fileSelected = true;
					}.bind(this)
				};
				
				Mojo.FilePicker.pickFile(params, this.controller.stageController);
				
			}else if (event.command == Mojo.Menu.helpCmd) {
				
				Event.stop(event);
				var openParams = {
					target: 'http://help.palm.com/device_info/index.html'
				};
				this.controller.serviceRequest('palm://com.palm.applicationManager', {
					method: 'open',
					parameters: {
						id: 'com.palm.app.help',
						params: openParams
					}
				});
			}

		} else if (event.type == Mojo.Event.commandEnable && 
		         (event.command == Mojo.Menu.helpCmd)) {
			event.stopPropagation();
		}
	},
	
	listSelectionHandler: function(event){
		var cert = event.item;
		Mojo.Log.info("listSelectionHandler " + Object.toJSON(cert));
		this.getDetails({
			'certificateId': cert.certificateId
		});
	},
	
	updateListSuccess: function(response){
		Mojo.Log.info("listcerts response " + Object.toJSON(response));
		$A(response.userCertificateStore).each(function(a){
			Mojo.Log.info("listcerts response " + Object.toJSON(a));
			a.displayCommonName = a.commonname ? a.commonname : a.organization;
                        if(a.displayCommonName===undefined){                                           
                            //Mojo.Log.info("inside Loop");                                                  
			    var alternate_name="";                                                  
			    for(var j in a.altname){                                                
			        alternate_name += a.altname[j] + ' ';                            
			    }   
			    a.displayCommonName=alternate_name;                            
			}                                             
			a.displayIssuerCommonName = a.issuerCommonName ? a.issuerCommonName : a.issuerOrganization; 
			this.certificateList.push(a);
		}.bind(this));
		
		if (this.certificateList.length == 0) {
			this.emptyText.show();
		}
		else {
			this.emptyText.hide();
		}
		
		this.controller.modelChanged(this.certificateListModel, this);
	},
	
	updateListFailure: function(response){
		Mojo.Log.info("getcertdetails response " + Object.toJSON(response));
	},
	
	updateList: function(){
		Mojo.Log.info("updatelist");
		this.certificateList.clear();
		AppAssistant.certificateService.listCerts({
			'category': 'user'
		}, this.updateListSuccess.bind(this), this.updateListFailure.bind(this), this.controller);
	},
	
	getDetailsSuccess: function(params, response){
		Mojo.Log.info("getDetailsSuccess response " + Object.toJSON(response));
		response.certificateId = params.certificateId;
		response.displayCommonName = response.subject.commonname ? response.subject.commonname : response.subject.organization;
		response.displayIssuerCommonName = response.issuer.commonname ? response.issuer.commonname : response.issuer.organization;
		this.controller.stageController.pushScene('details', response);
	},
	
	getDetailsFailure: function(params, response){
		Mojo.Log.info("getDetailsFailure response " + Object.toJSON(response));
	},
	
	getInstallSuccess: function(params, response){
		Mojo.Log.info("getInstallSuccess response install" + Object.toJSON(response));
		response.certificateFilename = params.certificateFilename;
		this.controller.stageController.pushScene('install', response);
	},
	
	getInstallFailure: function(params, response){
		Mojo.Log.info("getInstallFailure response install", Object.toJSON(params), Object.toJSON(response));
		
		if (response.errorCode == 14) {
			this.controller.showDialog({
				template: 'list/password-dialog',
				assistant: new PasswordDialogAssistant(this, params)
			});
		} else if (response.errorText == "com.palm.certificatemanager is not running.") {
		} else {
			var messageTemplate = new Template($L('The file #{fileName} cannot be opened because it is not a valid security certificate file format.'));
			var msg = messageTemplate.evaluate({
				fileName: params.certificateFilename.split('/').last()
			});
			this.controller.showAlertDialog({
				title: $L('Invalid certificate'),
				message: msg,
				choices: [{
					label: $L("OK"),
					type: 'dismiss'
				}, ]
			});
		}
	},
	
	getDetails: function(params){
		Mojo.Log.info("cert getdetails ", Object.toJSON(params));
		if ("certificateId" in params) {
		//			AppAssistant.certificateService.getCertDetails(params, this.getDetailsSuccess.bind(this), this.getDetailsFailure.bind(this), this.controller);
			this.controller.serviceRequest('palm://com.palm.certificatemanager', {
				method: 'getcertificatedetails',
				parameters: params,
				onSuccess: this.getDetailsSuccess.bind(this, params),
				onFailure: this.getDetailsFailure.bind(this, params)
			});
		} else {
		//			AppAssistant.certificateService.getCertDetails(params, this.getInstallSuccess.bind(this, params), this.getInstallFailure.bind(this, params), this.controller);
			this.controller.serviceRequest('palm://com.palm.certificatemanager', {
				method: 'getcertificatedetails',
				parameters: params,
				onSuccess: this.getInstallSuccess.bind(this, params),
				onFailure: this.getInstallFailure.bind(this, params)
			});
		}
		
	},
	
	activate: function(event){
		Mojo.Log.info("cert activate ", Object.toJSON(event));
		if (this.fileSelected == true) {
			this.getDetails({
				'certificateFilename': this.fileFullPath
			});
			delete this.fileSelected;
		} else {
			this.updateList();
		}
	},
	
	deactivate: function(event){
		Mojo.Log.info("cert deactivate ");
	},
	
	cleanup: function(event){
		Mojo.Log.info("cert cleanup ");
	},

});


