Ext.define("Ext.ux.form.field.DownloadPicker", {

    extend: "Ext.ux.form.field.UploadPicker",

    alias: [
        "widget.downloadpicker",
    ],

    triggers: {
        download: {
            cls: "x-ux-form-trigger-download",
            handler: "onDownloadClick",
            tooltip: ip2.i18n({
                da: "Download fil",
                en: "Donwload file"
            }),
            hidden: true,
            weight: 3,
            scope: "this",
            onClick: function() {

                var i_self = this;
                var args = arguments;
                var e = i_self.clickRepeater ? args[1] : args[0];
                var handler = i_self.handler;
                var i_field = i_self.field;

                if (handler && i_self.isFieldEnabled()) {

                    Ext.callback(i_self.handler, i_self.scope, [
                        i_field,
                        i_self,
                        e
                    ], 0, i_field);
                }
            }
        }
    },

    listeners: {
        afterrender: {
            fn: function(i_field) {

                var s_value = i_field.getValue();

                var i_trigger = i_field.getTrigger("download");

                if (i_trigger) {
                    i_trigger[Ext.isEmpty(s_value) ? "hide" : "show"]();
                }
            }
        },
        change: {
            fn: function(i_field, s_value) {

                var i_trigger = i_field.getTrigger("download");

                if (i_trigger) {
                    i_trigger[Ext.isEmpty(s_value) ? "hide" : "show"]();
                }
            }
        },
        enable: {
			fn: function(i_field) {

				var s_value = i_field.getValue();

				i_field.getTrigger("download")[Ext.isEmpty(s_value) ? "hide" : "show"]();
			},
			buffer: 10
		},
		disable: {
			fn: function(i_field) {
                
				i_field.getTrigger("download").hide();
			},
			buffer: 10
		},
		writeablechange: {
			fn: function(i_field, b_readOnly) {

				var s_value = i_field.getValue();

				if (!b_readOnly) {
				    i_field.getTrigger("download")[Ext.isEmpty(s_value) ? "hide" : "show"]();
				}
			},
			buffer: 10
		}
    },

    onDownloadClick: function() {

		var i_self = this;

        var s_value = i_self.getValue();
        
        var anchor = document.createElement("a");
        anchor.href = s_value;
        anchor.download = s_value;
        document.body.appendChild(anchor);
        anchor.click();

        document.body.removeChild(anchor);
	}
})