Ext.namespace('Zarafa.plugins.fetchmail');

/**
 * @class Zarafa.plugins.fetchmail.ABOUT
 *
 * The copyright string holding the copyright notice for the Zarafa/Kopano fetchmail Plugin.
 */
Zarafa.plugins.fetchmail.ABOUT = ""
	+ "<p>Copyright (C) 2017  Oliver Asselmann &lt;olia@ktah.net&gt;</p>"
	+ "<p>This program is free software: you can redistribute it and/or modify "
	+ "it under the terms of the GNU Affero General Public License as "
	+ "published by the Free Software Foundation, either version 3 of the "
	+ "License, or (at your option) any later version.</p>"

	+ "<p>This program is distributed in the hope that it will be useful, "
	+ "but WITHOUT ANY WARRANTY; without even the implied warranty of "
	+ "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the "
	+ "GNU Affero General Public License for more details.</p>"

	+ "<p>You should have received a copy of the GNU Affero General Public License "
	+ "along with this program. If not, see <a href=\"http://www.gnu.org/licenses/\" target=\"_blank\">http://www.gnu.org/licenses/</a>.</p>"
	+ "<hr>"
	+ "<p>The fetchmail plugin contains the following third-party components:</p><br>"
	+ "<p>Fetchmail Plugin Icon is from the <a href='https://www.iconfinder.com/iconsets/mail-icons-2'>\"Mail Icons\"</a> set by \"Benjamin STAWARZ\" licensed under <a href='http://creativecommons.org/licenses/by/3.0/'>CC BY 3.0</a></p>"
	+ "<p>Status Icons are from the <a href='https://www.iconfinder.com/iconsets/flat-actions-icons-9'>\"Flat Icons\"</a> set by <a href='https://www.iconfinder.com/iconpack'>\"iconpack\"</a> which is licensed free for commercial use."
	;
	
	
Ext.namespace('Zarafa.plugins.fetchmail');

/**
 * @class Zarafa.plugins.fetchmail.FetchmailPlugin
 * @extends Zarafa.core.Plugin
 *
 * Plugin allows the user to configure one or more accounts to be polled via fetchmail inside of Kopano Webapp
 */
Zarafa.plugins.fetchmail.FetchmailPlugin = Ext.extend(Zarafa.core.Plugin, {

	
	/**
     * @constructor
     * @param {Object} config Configuration object
     *
     */
    constructor : function (config)
    {
            config = config || {};
            Zarafa.plugins.fetchmail.FetchmailPlugin.superclass.constructor.call(this, config);
    },
    
	/**
	 * Called after constructor.
	 * Registers insertion points.
	 * @protected
	 */
	initPlugin : function()
	{
		// Register categories for the settings
		this.registerInsertionPoint('context.settings.categories', this.createSettingsCategory, this);
		
		// register my modify/create dialog
		Zarafa.core.data.SharedComponentType.addProperty('plugin.fetchmail.dialogs.accountdialogcontentpanel');
		
		Zarafa.plugins.fetchmail.FetchmailPlugin.superclass.initPlugin.apply(this, arguments);
	},
	
	/**
	 * Bid for the type of shared component and the given record.
	 * @param {Zarafa.core.data.SharedComponentType} type Type of component a context can bid for.
	 * @param {Ext.data.Record} record Optionally passed record.
	 * @returns {Number}
	 */
	bidSharedComponent : function (type, record)
	{
		var bid = -1;
		switch (type) {
			case Zarafa.core.data.SharedComponentType['plugin.fetchmail.dialogs.accountdialogcontentpanel']:
				bid = 1;
				break;
		}
		return bid;
	},

	/**
	 * Will return the reference to the shared component.
	 * Based on the type of component requested a component is returned.
	 * @param {Zarafa.core.data.SharedComponentType} type Type of component a context can bid for.
	 * @param {Zarafa.mail.dialogs.MailCreateContentPanel} owner Optionally passed panel
	 * @return {Ext.Component} Component
	 */
	getSharedComponent : function(type, record) {
		var component;

		switch(type) {
			case Zarafa.core.data.SharedComponentType['plugin.fetchmail.dialogs.accountdialogcontentpanel']:
				component = Zarafa.plugins.fetchmail.dialogs.FetchmailAccountDialogContentPanel;
				break;
		}

		return component;
	},

	/**
	 * Creates a category in settings for fetchmail
	 * @return {settingsfetchmailcategory}
	 */
	createSettingsCategory : function(insertionName, settingsMainPanel, settingsContext)
	{
		return {
			xtype : 'zarafa.settingsfetchmailcategory',
			settingsContext : settingsContext
		};
	}
});

Zarafa.onReady(function() {
	//the protocol/polling type is saved as a constant in the DB
	Zarafa.plugins.fetchmail.FETCHMAIL_PROTOCOL_IMAP = 1;
	Zarafa.plugins.fetchmail.FETCHMAIL_PROTOCOL_IMAPS = 2;
	Zarafa.plugins.fetchmail.FETCHMAIL_PROTOCOL_POP3 = 5;
	Zarafa.plugins.fetchmail.FETCHMAIL_PROTOCOL_POP3S = 6;
	Zarafa.plugins.fetchmail.FETCHMAIL_POLLING_TYPE_FETCHALL = 1;
	Zarafa.plugins.fetchmail.FETCHMAIL_POLLING_TYPE_KEEP = 5;
	
	//the protocol/polling type integer <=> string constants
	Zarafa.plugins.fetchmail.FETCHMAIL_PROTOCOL_IMAP_STRING = "IMAP";
	Zarafa.plugins.fetchmail.FETCHMAIL_PROTOCOL_IMAPS_STRING = "IMAP+SSL";
	Zarafa.plugins.fetchmail.FETCHMAIL_PROTOCOL_POP3_STRING = "POP3";
	Zarafa.plugins.fetchmail.FETCHMAIL_PROTOCOL_POP3S_STRING = "POP3+SSL";
	Zarafa.plugins.fetchmail.FETCHMAIL_POLLING_TYPE_FETCHALL_STRING = "FETCHALL";
	Zarafa.plugins.fetchmail.FETCHMAIL_POLLING_TYPE_KEEP_STRING = "KEEP";
	
	//success/error constants
	Zarafa.plugins.fetchmail.FETCHMAIL_ACCOUNT_SAVE_SUCCESS_RESPONSE = 42;
	Zarafa.plugins.fetchmail.FETCHMAIL_ACCOUNT_SAVE_ERROR_PARAMETER_RESPONSE = 43;
	Zarafa.plugins.fetchmail.FETCHMAIL_ACCOUNT_DELETE_SUCCESS_RESPONSE = 142;
	Zarafa.plugins.fetchmail.FETCHMAIL_ACCOUNT_POLL_NOW_SUCCESS_RESPONSE = 1142;
	
	
	container.registerPlugin(new Zarafa.core.PluginMetaData({
		name : 'fetchmail',
		displayName : _('Fetchmail Plugin', 'plugin_fetchmail'),
		about : Zarafa.plugins.fetchmail.ABOUT,
		pluginConstructor : Zarafa.plugins.fetchmail.FetchmailPlugin
	}));
});
Ext.namespace('Zarafa.plugins.fetchmail.data');

Zarafa.plugins.fetchmail.data.FetchmailAccountRecordFields = [
	{name: 'entryid', type: 'string'},                                                         
	{name: 'kopano_uid', type: 'string'},
	{name: 'kopano_mail', type: 'string'},
	{name: 'src_server', type: 'string'},
	{name: 'src_port', type: 'string'},
	{name: 'src_protocol', type: 'string'},
	{name: 'src_polling_type', type: 'string'},
	{name: 'src_user', type: 'string'},
	{name: 'src_password', type: 'string'},
	{name: 'polling_freq', type: 'string'},
	{name: 'last_polling', type: 'date', dateFormat: 'timestamp'},
	{name: 'last_update', type: 'date', dateFormat: 'timestamp'},
	{name: 'last_status_code', type: 'string'},
	{name: 'last_log_message', type: 'string'}
];

Zarafa.plugins.fetchmail.data.FetchmailAccountRecord = Ext.extend(Zarafa.core.data.IPMRecord, {});
Zarafa.core.data.RecordCustomObjectType.addProperty('ZARAFA_FETCHMAIL');
Zarafa.core.data.RecordFactory.addFieldToCustomType(Zarafa.core.data.RecordCustomObjectType.ZARAFA_FETCHMAIL, Zarafa.plugins.fetchmail.data.FetchmailAccountRecordFields);

Zarafa.core.data.RecordFactory.addListenerToCustomType(Zarafa.core.data.RecordCustomObjectType.ZARAFA_FETCHMAIL, 'createphantom', function(record)
{
	// Phantom records must always be marked as opened (they contain the full set of data)
	record.afterOpen();
});

Zarafa.core.data.RecordFactory.setBaseClassToCustomType(Zarafa.core.data.RecordCustomObjectType.ZARAFA_FETCHMAIL, Zarafa.plugins.fetchmail.data.FetchmailAccountRecord);
Ext.namespace('Zarafa.plugins.fetchmail.data');

/**
 * @class Zarafa.plugins.fetchmail.data.FetchmailAccountStore
 * @extends Zarafa.core.data.ListModuleStore
 * @xtype fetchmail.accountstore
 * Store specific for Fetchmail Plugin which creates a FetchmailAccountRecord.
 */
Zarafa.plugins.fetchmail.data.FetchmailAccountStore = Ext.extend(Zarafa.core.data.ListModuleStore, {
	/**
	 * @constructor
	 * @param config Configuration object
	 */
	constructor : function(config)
	{
		config = config || {};

		Ext.applyIf(config, {
			autoLoad : true,
			remoteSort: false,
			reader : new Zarafa.plugins.fetchmail.data.JsonAccountReader(),
			writer : new Zarafa.core.data.JsonWriter(),
			proxy  : new Zarafa.core.data.IPMProxy({
				listModuleName: 'pluginfetchmailmodule',
				itemModuleName: 'pluginfetchmailmodule'
			})
		});

		Zarafa.plugins.fetchmail.data.FetchmailAccountStore.superclass.constructor.call(this, config);
	}
});

Ext.reg('fetchmail.accountstore', Zarafa.plugins.fetchmail.data.FetchmailAccountStore);
Ext.namespace('Zarafa.plugins.fetchmail.data');

/**
 * @class Zarafa.plugins.fetchmail.data.ResponseHandler
 * @extends Zarafa.core.data.AbstractResponseHandler
 *
 * Fetchmail plugin specific response handler.
 */
Zarafa.plugins.fetchmail.data.FetchmailResponseHandler = Ext.extend(Zarafa.core.data.AbstractResponseHandler, {

	/**
	 * @cfg {Function} successCallback The function which
	 * will be called after success request.
	 */
	successCallback : null,
	
	/**
	 * @param {Object} response Object contained the response data.
	 */
	doAccountsave : function(response) {
		this.successCallback(response);
	},
	
	/**
	 * @param {Object} response Object contained the response data.
	 */
	doAccountdelete : function(response) {
		this.successCallback(response);
	},	
	
	/**
	 * @param {Object} response Object contained the response data.
	 */
	doAccountpollnow : function(response) {
		this.successCallback(response);
	}	
	
	



});

Ext.reg('fetchmail.responsehandler', Zarafa.plugins.fetchmail.data.FetchmailResponseHandler);
Ext.namespace('Zarafa.plugins.fetchmail.data');

/**
 * @class Zarafa.plugins.fetchmail.data.JsonAccountReader
 * @extends Zarafa.core.data.JsonReader
 */
Zarafa.plugins.fetchmail.data.JsonAccountReader = Ext.extend(Zarafa.core.data.JsonReader, {
        /**
         * @cfg {Zarafa.core.data.RecordCustomObjectType} customObjectType The custom object type
         * which represents the {@link Ext.data.Record records} which should be created using
         * {@link Zarafa.core.data.RecordFactory#createRecordObjectByCustomType}.
         */
        customObjectType : Zarafa.core.data.RecordCustomObjectType.ZARAFA_FETCHMAIL,

        /**
         * @constructor
         * @param {Object} meta Metadata configuration options.
         * @param {Object} recordType (optional) Optional Record type matches the type
         * which must be read from response. If no type is given, it will use the
         * record type for the {@link Zarafa.core.data.RecordCustomObjectType#ZARAFA_FETCHMAIL}.
         */
        constructor : function(meta, recordType)
        {
                meta = Ext.applyIf(meta || {}, {
                        dynamicRecord : false
                });

		recordType = Zarafa.core.data.RecordFactory.getRecordClassByCustomType(Zarafa.core.data.RecordCustomObjectType.ZARAFA_FETCHMAIL);

                Zarafa.plugins.fetchmail.data.JsonAccountReader.superclass.constructor.call(this, meta, recordType);
        }
});
Ext.namespace('Zarafa.plugins.fetchmail.dialogs');

/**
 * @class Zarafa.plugins.fetchmail.dialogs.FetchmailAccountDialogContentPanel
 * @extends Zarafa.core.ui.ContentPanel
 * @xtype fetchmailplugin.accountdialogcontentpanel
 * 
 * Dialog to create or modify a fetchmail account.
 * 
 * The Dialog displays an FetchmailAccountDialogDetailsPanel inside an ContentPanel.
 */
Zarafa.plugins.fetchmail.dialogs.FetchmailAccountDialogContentPanel = Ext.extend(Zarafa.core.ui.ContentPanel, {

    /**
     * @constructor
     * @param config Configuration structure
     */
    constructor: function (config) {
        config = config || {};
        
        var title = config.record.get('src_user');
        if(title == null)
        	title = dgettext('plugin_fetchmail', 'New Account');
        
        Ext.applyIf(config, {

            xtype: 'fetchmailplugin.accountdialogcontentpanel',
            layout    : 'fit',
            modal     : true,
            width     : 500,
            height	  : 500,
            title     : dgettext('plugin_fetchmail', title),
            items     : [{
                xtype: 'fetchmailplugin.fetchmailaccountdialogdetailspanel',
                record : config.record,
                buttonAlign: 'center',
				buttons: [{
					text: _('Save', 'plugin_fetchmail'),
					handler: this.onSaveBtn,
					scope: this
				},{
					text: _('Cancel', 'plugin_fetchmail'),
					handler: this.close,
					scope: this
				}]
            }]
        });

        Zarafa.plugins.fetchmail.dialogs.FetchmailAccountDialogContentPanel.superclass.constructor.call(this, config);
    },
    
	/**
	 * Save form function that either creates or modifys an existing entry on the server.
	 */
    onSaveBtn: function()
	{
		var form = this.get(0);

		form.saveFetchmailAccount();
	}
    
});

Ext.reg('fetchmailplugin.accountdialogcontentpanel', Zarafa.plugins.fetchmail.dialogs.FetchmailAccountDialogContentPanel);Ext.namespace('Zarafa.plugins.fetchmail.dialogs');

/**
 * @class Zarafa.plugins.fetchmail.dialogs.FetchmailAccountDialogContentPanel
 * @extends Ext.form.FormPanel
 * @xtype fetchmailplugin.fetchmailaccountdialogdetailspanel
 *
 * FormPanel which is shown inside FetchmailAccountDialogContentPanel.
 * 
 * The Panel displays either an already existing fetchmail account, or an empty form to create a new one. 
 * 
 */
Zarafa.plugins.fetchmail.dialogs.FetchmailAccountDialogDetailsPanel = Ext.extend(Ext.form.FormPanel, {

    /**
     * @cfg {Zarafa.plugins.fetchmail.data.FetchmailAccountRecord} record The account record which
     * is either being displayed or created.
     */
    record : null,

    /**
     * @constructor
     * @param config Configuration structure
     */
    constructor : function (config) {
        config = config || {};

        Ext.applyIf(config, {
            xtype : 'fetchmailplugin.fetchmailaccountdialogdetailspanel',
            layout : 'form',
            labelAlign : 'top',
            anchor: '100%',            
            defaults : {
            	anchor: '100%'
            },
            items : [{
            	xtype:'textfield',
                fieldLabel : dgettext('plugin_fetchmail', 'EntryID'),
                name : "entryid",
                id : 'entryid',
                hideLabel: true,
                hidden : true,
                readOnly: true            
            }, {
            	xtype:'textfield',
                fieldLabel : dgettext('plugin_fetchmail', 'User mail address'),
                name : "kopano_mail",
                id : 'kopano_mail',
                hideLabel: true,
                hidden : true,
                readOnly: true,
                value : container.getUser().getEmailAddress()
            }, {
            	xtype:'textfield',
                fieldLabel : dgettext('plugin_fetchmail', 'Mail Server'),
                name : "src_server",
                id : 'src_server',
                listeners : {
    				'change': function() {
    					this.resetErrorMessage('src_server');
    				},
    				scope: this
    			}
            }, {
            	//build an hbox to show protocol/port next to each other
            	xtype: 'container',
            	layout: 'hbox',
            	align: 'middle',
            	pack: 'center',
                border: false,
                defaults: {
                	layout: 'form',
                	flex: 0.5,
                	border: false
                },
                //nest the items so that form layout is used for the actual displayfield/combobox
                items: [{ 
                	items: [{ 
                		xtype: 'combo',
                		fieldLabel: dgettext('plugin_fetchmail', 'Mail Protocol'),
                		hiddenName: 'src_protocol',
                		mode : 'local',
                		ref : '../../src_protocol',
                		id : 'src_protocol',
                		store: new Ext.data.SimpleStore({
                			data: [
                			       [Zarafa.plugins.fetchmail.FETCHMAIL_PROTOCOL_IMAP, Zarafa.plugins.fetchmail.FETCHMAIL_PROTOCOL_IMAP_STRING],
                			       [Zarafa.plugins.fetchmail.FETCHMAIL_PROTOCOL_IMAPS, Zarafa.plugins.fetchmail.FETCHMAIL_PROTOCOL_IMAPS_STRING],
                			       [Zarafa.plugins.fetchmail.FETCHMAIL_PROTOCOL_POP3, Zarafa.plugins.fetchmail.FETCHMAIL_PROTOCOL_POP3_STRING],
                			       [Zarafa.plugins.fetchmail.FETCHMAIL_PROTOCOL_POP3S, Zarafa.plugins.fetchmail.FETCHMAIL_PROTOCOL_POP3S_STRING]
                			       ],
                			       id: 0,
                			       fields: ['protocol_id', 'protocol_text']
                		}),
                		valueField: 'protocol_id',
                		displayField: 'protocol_text',
                		triggerAction: 'all',
                		editable: false,
                		listeners : {
                			'change': function() {
                				this.resetErrorMessage('src_protocol');
                				//automatically set a default port value after choosing a protocol
                				switch(this.src_protocol.getValue()) {
                					case  Zarafa.plugins.fetchmail.FETCHMAIL_PROTOCOL_IMAP:
                						this.src_port.setValue('143');
                						break;
                					case Zarafa.plugins.fetchmail.FETCHMAIL_PROTOCOL_IMAPS:
                						this.src_port.setValue('993');
                						break;
                					case Zarafa.plugins.fetchmail.FETCHMAIL_PROTOCOL_POP3:
                						this.src_port.setValue('110');
                						break;
                					case Zarafa.plugins.fetchmail.FETCHMAIL_PROTOCOL_POP3S:
                						this.src_port.setValue('995');
                						break;
                				}
                            },
                			scope: this
                		}
                	}]
                }, {
                	items: [{
	                	xtype: 'textfield',
            			name : 'src_port',
	                   	fieldLabel : dgettext('plugin_fetchmail', 'Server Port'),
	                   	ref : '../../src_port',
	                   	id: 'src_port',
	                    listeners : {
	        				'change': function() {
	        					this.resetErrorMessage('src_port');
	        				},
	        				scope: this
	        			}
                	}]
                }] 
            }, {
            	xtype:'textfield',
                fieldLabel : dgettext('plugin_fetchmail', 'Account Login'),
                name : "src_user",
                id : 'src_user',
                listeners : {
    				'change': function() {
    					this.resetErrorMessage('src_user');
    				},
    				scope: this
    			}
            }, {
            	xtype:'textfield',
                fieldLabel : dgettext('plugin_fetchmail', 'Account Password'),
                name : "src_password",
                id : 'src_password',
                inputType: 'password',
                listeners : {
    				'change': function() {
    					this.resetErrorMessage('src_password');
    				},
    				scope: this
    			}
            }, {
            	xtype:'textfield',
                fieldLabel : dgettext('plugin_fetchmail', 'Polling Frequency (in minutes)'),
                name : "polling_freq",
                id : 'polling_freq',
                listeners : {
    				'change': function() {
    					this.resetErrorMessage('polling_freq');
    				},
    				scope: this
    			}
            }, {
            	xtype: 'combo',
            	fieldLabel: dgettext('plugin_fetchmail', 'Polling Type (Warning: FETCHALL deletes the mails from the Remote Server)'),
            	hiddenName: 'src_polling_type',
            	id : 'src_polling_type',
            	mode : 'local',
            	store: new Ext.data.SimpleStore({
            		data: [
            		    [Zarafa.plugins.fetchmail.FETCHMAIL_POLLING_TYPE_FETCHALL, Zarafa.plugins.fetchmail.FETCHMAIL_POLLING_TYPE_FETCHALL_STRING],
            			[Zarafa.plugins.fetchmail.FETCHMAIL_POLLING_TYPE_KEEP, Zarafa.plugins.fetchmail.FETCHMAIL_POLLING_TYPE_KEEP_STRING]
            		],
            		id: 0,
            		fields: ['polling_type_id', 'polling_type_text']
            	}),
            	valueField: 'polling_type_id',
            	displayField: 'polling_type_text',
            	triggerAction: 'all',
            	editable: false,
                listeners : {
    				'change': function() {
    					this.resetErrorMessage('src_polling_type');
    				},
    				scope: this
    			}
            }, {
            	xtype : 'textarea',
                fieldLabel : dgettext('plugin_fetchmail', 'Last Log Message'),
                autoHeight : true,
                readOnly : true,
                hidden : true,
    			hideMode : 'visibility',
    			grow : true,
                growMax : 100,
                name : "last_log_message",
                ref : 'last_log_message',
                emptyText: _('No Log message found.', 'plugin_fetchmail')
            }, {
    			hideLabel : true,
    			hidden : true,
    			hideMode : 'visibility',
    			xtype : 'displayfield',
    			ref : 'error_notification',
    			name : 'error_notification',
    			cls: 'zarafa-smime-invalid-text',
    			value: _('Something went wrong. Please contact your Administrator.', 'plugin_fetchmail')
            }],
            listeners : {
                afterlayout : this.onAfterLayout,
                scope : this
            }
        });

        Zarafa.plugins.fetchmail.dialogs.FetchmailAccountDialogDetailsPanel.superclass.constructor.call(this, config);
    },

    /**
     * Function which handles the after layout event of FetchmailAccountDialogDetailsPanel.
     * Loads the information out of a FetchmailAccountRecord. Also hides the last_log_message window if its empty.
     */
    onAfterLayout : function ()
    {
        this.getForm().loadRecord(this.record);
        //creating a new account is strange if a non-editable last_log_message field is shown.
        if(this.last_log_message.getValue() != '')
			this.last_log_message.show();
    },
    
    
	/**
	 * Reset the error message when user changes one of the fields.
	 */
	resetErrorMessage: function(id)
	{
		var cmp = Ext.getCmp(id);
		if(cmp)
			cmp.getEl().removeClass('fetchmail-parameter-false');
		this.error_notification.hide();
		this.error_notification.setValue(_('Something went wrong. Please contact your Administrator.', 'plugin_fetchmail'));
		
	},
    
	/**
	 * Sends the account information to the backend to validate&save.
	 */
    saveFetchmailAccount: function()
	{
    	var data = this.getForm().getFieldValues();
		
    	container.getRequest().singleRequest(
    		'pluginfetchmailmodule',
			'save',
			data,
			new Zarafa.plugins.fetchmail.data.FetchmailResponseHandler({
				successCallback : this.onSaveFetchmailAccountRequest.createDelegate(this)
				})
		);
	},
	
	/**
	 * Handler for successCallback of the saveFetchmailAccount request.
	 */
	onSaveFetchmailAccountRequest: function(response) {
		if (response.code === Zarafa.plugins.fetchmail.FETCHMAIL_ACCOUNT_SAVE_SUCCESS_RESPONSE) {
			container.getNotifier().notify('info.saved', _('Fetchmail Message', 'plugin_fetchmail'), _('Account saved succesfully!', 'plugin_fetchmail'));
			this.dialog.close();
		} else if (response.code === Zarafa.plugins.fetchmail.FETCHMAIL_ACCOUNT_SAVE_ERROR_PARAMETER_RESPONSE){
			this.error_notification.setValue(_(response.message, 'plugin_fetchmail'));
			var cmp = Ext.getCmp(response.parameter);
			if(cmp)
				cmp.getEl().addClass('fetchmail-parameter-false');
			this.error_notification.show();
		} else {
			this.error_notification.setValue(_('Something went wrong. Please contact your Administrator.', 'plugin_fetchmail'));
			this.error_notification.show();
		}
	}
    
});

Ext.reg('fetchmailplugin.fetchmailaccountdialogdetailspanel', Zarafa.plugins.fetchmail.dialogs.FetchmailAccountDialogDetailsPanel);Ext.namespace('Zarafa.plugins.fetchmail.settings');

/**
 * @class Zarafa.plugins.fetchmail.settings.SettingsFetchmailCategory
 * @extends Zarafa.settings.ui.SettingsCategory
 * @xtype zarafa.settingsfetchmailcategory
 *
 * Creates a new SettingsCategory to show the SettingsFetchmailWidget.
 * 
 */
Zarafa.plugins.fetchmail.settings.SettingsFetchmailCategory = Ext.extend(Zarafa.settings.ui.SettingsCategory, {
	/**
	 * @constructor
	 * @param {Object} config Configuration object
	 */
	constructor : function(config)
	{
		config = config || {};

		Ext.applyIf(config, {
			title : _('Fetchmail', 'plugin_fetchmail'),
			iconCls : 'icon_fetchmail_settings',
			xtype : 'zarafa.settingsfetchmailcategory',
			items : [{
				xtype : 'zarafa.settingsfetchmailwidget',
				settingsContext : config.settingsContext
			},
				container.populateInsertionPoint('context.settings.category.fetchmail', this)
			]
		});

		Zarafa.plugins.fetchmail.settings.SettingsFetchmailCategory.superclass.constructor.call(this, config);
	}
});

Ext.reg('zarafa.settingsfetchmailcategory', Zarafa.plugins.fetchmail.settings.SettingsFetchmailCategory);
Ext.namespace('Zarafa.plugins.fetchmail.settings');

/**
 * @class Zarafa.plugins.fetchmail.settings.SettingsFetchmailWidget
 * @extends Zarafa.settings.ui.SettingsWidget
 * @xtype zarafa.settingsfetchmailwidget
 *
 * The widget displayed in the kopano Settings to configure Fetchmail.
 * 
 */
Zarafa.plugins.fetchmail.settings.SettingsFetchmailWidget = Ext.extend(Zarafa.settings.ui.SettingsWidget, {

	/**
	 * @constructor
	 * @param {Object} config Configuration object
	 */
	constructor : function(config)
	{
		config = config || {};

		var store = new Zarafa.plugins.fetchmail.data.FetchmailAccountStore();
		Ext.applyIf(config, {
			title : _('Fetchmail Configuration', 'plugin_fetchmail'),
			items : [{
				xtype : 'container',
				layout: 'fit',
				itemId: 'container',
				items : [{
					xtype : 'grid',
					name : _('Accounts', 'plugin_fetchmail'),
					ref : '../accountGrid',
					height : 400,
					itemId : 'accountGrid', 
					store : store,
					viewConfig : {
						forceFit : true,
						deferEmptyText: false,
						emptyText: '<div class="emptytext">' + _('No accounts configured', 'plugin_fetchmail') + '</div>',
						getRowClass: function(record) {
							//check "man fetchmail" why we only care for status codes greater than 1
							if(record.get('last_status_code') > 1)
								return 'fetchmail-grid-polling-error';
					    } 
					},
					columns : [{
						dataIndex : 'last_status_code',
						header : '&#160;',
						resizable : false,
						sortable : false,
						hideable : false,
						width : 10,
						renderer : function(value, metadata, record, rowIndex, colIndex, store) {
							if(value < 0)
								metadata.css = metadata.css + ' icon_fetchmail_unknown ';
							else if(value > 1)
								metadata.css = metadata.css + ' icon_fetchmail_failure ';
							else
								metadata.css = metadata.css + ' icon_fetchmail_success '; 
							
							metadata.attr = 'ext:qtip="' + (value) + '"';
							
							return '&nbsp;';
						}
					},{
						dataIndex : 'src_server',
						header : _('Mail Server', 'plugin_fetchmail'),
						renderer : Ext.util.Format.htmlEncode
					},{
						dataIndex : 'src_port',
						header : _('Server Port', 'plugin_fetchmail'),
						renderer : Ext.util.Format.htmlEncode,
						width: 70
					},{
						dataIndex : 'src_protocol',
						header : _('Mail Protocol', 'plugin_fetchmail'),
						width: 80,
						renderer : function($value) {
							switch(parseInt($value)) {
								case Zarafa.plugins.fetchmail.FETCHMAIL_PROTOCOL_IMAP:
									return Zarafa.plugins.fetchmail.FETCHMAIL_PROTOCOL_IMAP_STRING;
									break;
								case Zarafa.plugins.fetchmail.FETCHMAIL_PROTOCOL_IMAPS:
									return Zarafa.plugins.fetchmail.FETCHMAIL_PROTOCOL_IMAPS_STRING;
									break;
								case Zarafa.plugins.fetchmail.FETCHMAIL_PROTOCOL_POP3:
									return Zarafa.plugins.fetchmail.FETCHMAIL_PROTOCOL_POP3_STRING;
									break;
								case Zarafa.plugins.fetchmail.FETCHMAIL_PROTOCOL_POP3S:
									return Zarafa.plugins.fetchmail.FETCHMAIL_PROTOCOL_POP3S_STRING;
									break;
								default:
									return _('Unknown Polling Type', 'plugin_fetchmail');
										
							}
						}
					},{
						dataIndex : 'src_polling_type',
						header : _('Polling Type', 'plugin_fetchmail'),
						width: 80,
						renderer : function($value) {
							switch(parseInt($value)) {
								case Zarafa.plugins.fetchmail.FETCHMAIL_POLLING_TYPE_FETCHALL:
									return Zarafa.plugins.fetchmail.FETCHMAIL_POLLING_TYPE_FETCHALL_STRING;
									break;
								case Zarafa.plugins.fetchmail.FETCHMAIL_POLLING_TYPE_KEEP:
									return Zarafa.plugins.fetchmail.FETCHMAIL_POLLING_TYPE_KEEP_STRING;
									break;
								default:
									return _('Unknown Polling Type', 'plugin_fetchmail');
										
							}
						}
					},{
						dataIndex : 'src_user',
						header : _('Account Login', 'plugin_fetchmail'),
						renderer : Ext.util.Format.htmlEncode
					},{
						dataIndex : 'polling_freq',
						header : _('Polling Frequency', 'plugin_fetchmail'),
						renderer : Ext.util.Format.htmlEncode
					},{
						dataIndex : 'last_polling',
						header : _('Last Polling', 'plugin_fetchmail'),
						renderer : Ext.util.Format.htmlEncode,
						width: 220
					},{
						dataIndex : 'last_log_message',
						header : _('Last Log Message', 'plugin_fetchmail'),
						renderer : Ext.util.Format.htmlEncode
					}],
					buttons : [{
						text : _('New Account', 'plugin_fetchmail'),
						ref : '../../../newAccountBtn',
						handler : this.onNewAccountBtn,
						scope : this
					},{
						text : _('Modify', 'plugin_fetchmail'),
						ref : '../../../modifyBtn',
						handler : this.onModifyBtn,
						scope : this
					},{
						text : _('Remove Account', 'plugin_fetchmail'),
						ref : '../../../removeAccountBtn',
						handler : this.onRemoveAccountBtn,
						scope : this
					},{
						text : _('Poll Now', 'plugin_fetchmail'),
						ref : '../../../pollNowBtn',
						handler : this.onPollNowBtn,
						scope : this
					},{
						text : _('Refresh', 'plugin_fetchmail'),
						ref : '../../../refresh',
						handler : this.onRefresh,
						scope : this
					}],
					listeners   : {
						rowdblclick: this.onRowDblClick,
						scope      : this
					}
				}]
			}]
		});

		Zarafa.plugins.fetchmail.settings.SettingsFetchmailWidget.superclass.constructor.call(this, config);
	},
	
	/**
	 * Function which handles the click event on the "New Account" button, displays
	 * a Dialog for the user to add a new entry.
	 */
	onNewAccountBtn : function()
	{
		//creates an empty FetchmailAccountRecord and then calls the same function to modify.
		this.showModifyCreateDialog(new Zarafa.plugins.fetchmail.data.FetchmailAccountRecord({}));
	},


	/**
	 * Function which handles the click event on the "Modify" button, displays
	 * a Dialog for the user to modify the existing entry.
	 */
	onModifyBtn : function()
	{
		this.showModifyCreateDialog(this.getComponent('container').getComponent('accountGrid').getSelectionModel().getSelected());
	},

	/**
	 * Function which handles the click event on the "Remove Account" button, removes the 
	 * account from the Store.
	 */
	onRemoveAccountBtn : function()
	{
		var rc = this.getComponent('container').getComponent('accountGrid').getSelectionModel().getSelected();
    	container.getRequest().singleRequest(
        		'pluginfetchmailmodule',
    			'delete',
    			rc.data['entryid'],
    			new Zarafa.plugins.fetchmail.data.FetchmailResponseHandler({
    				successCallback : this.onDeleteFetchmailAccountRequest.createDelegate(this)
    				})
    		);
		
		
	},

	/**
	 * Function which handles the click event on the "Poll Now" button, sets the last_polling timestamp to (last_polling - 2*polling_frequency).
	 * After that the background task/cronjob/daemon should poll this account.
	 */
	onPollNowBtn : function()
	{
		var rc = this.getComponent('container').getComponent('accountGrid').getSelectionModel().getSelected();
    	container.getRequest().singleRequest(
        		'pluginfetchmailmodule',
    			'pollnow',
    			rc.data['entryid'],
    			new Zarafa.plugins.fetchmail.data.FetchmailResponseHandler({
    				successCallback : this.onPollNowRequest.createDelegate(this)
    				})
    		);
	},
	
	/**
	 * Function which refreshes the store records from the server.
	 */
	onRefresh : function()
	{
		this.accountGrid.getStore().load();
	},

	/**
	 * Function is called if a row in the grid gets double clicked and opens the modify Dialog.
	 * @param {Ext.grid.GridPanel} grid The Grid on which the user double-clicked
	 * @param {Number} rowIndex The Row number on which was double-clicked.
	 */
	onRowDblClick : function (grid, rowIndex)
	{
		var record = grid.getStore().getAt(rowIndex);
		this.showModifyCreateDialog(record);
	},
	
	/**
	 * Handler for successCallback of the delete FetchmailAccount request.
	 */
	onDeleteFetchmailAccountRequest: function(response) {
		if (response.code === Zarafa.plugins.fetchmail.FETCHMAIL_ACCOUNT_DELETE_SUCCESS_RESPONSE) {
			container.getNotifier().notify('info.saved', _('Fetchmail Message', 'plugin_fetchmail'), _('Account deleted succesfully.', 'plugin_fetchmail'));
			this.onRefresh();
		} else {
			container.getNotifier().notify('error', _('Fetchmail Message', 'plugin_fetchmail'), _(response.error, 'plugin_fetchmail'));
			this.onRefresh();
		}
	},
	
	/**
	 * Handler for successCallback of the pollNow request.
	 */
	onPollNowRequest: function(response) {
		if (response.code === Zarafa.plugins.fetchmail.FETCHMAIL_ACCOUNT_POLL_NOW_SUCCESS_RESPONSE) {
			container.getNotifier().notify('info.saved', _('Fetchmail Message', 'plugin_fetchmail'), _('Account marked for immediate polling.', 'plugin_fetchmail'));
			this.onRefresh();
		} else {
			container.getNotifier().notify('error', _('Fetchmail Message', 'plugin_fetchmail'), _(response.error, 'plugin_fetchmail'));
			this.onRefresh();
		}
	},
	
	/**
	 * Function wich displays an FetchmailAccountDialogContentPanel.
	 * @param {FetchmailAccountRecord} record A record to display
	 */
	showModifyCreateDialog : function(record)
	{
		Zarafa.core.data.UIFactory.openLayerComponent(Zarafa.core.data.SharedComponentType['plugin.fetchmail.dialogs.accountdialogcontentpanel'], undefined, {
			manager : Ext.WindowMgr,
			record : record,
			listeners : {
				'destroy': this.onRefresh,
	 			scope: this
			}
		});		
	}
});

Ext.reg('zarafa.settingsfetchmailwidget', Zarafa.plugins.fetchmail.settings.SettingsFetchmailWidget);
