(function () {
    var Ext = window.Ext4 || window.Ext;

    /**
     * @private
     */
    Ext.define('Rally.ui.detail.metafield.OwnerMetaField', {
        extend: 'Rally.ui.detail.FieldsetContainer',
        alias: 'widget.rallydetailownermetafieldedpcomplete',
        requires: [
            'Rally.data.util.Record'
        ],
        name: 'Owner',
        cls: 'detailFieldContainer detailOwnerField',
        config: {
            record: undefined
        },
        displayName: 'OWNER',
        constructor: function (config) {
            this.initConfig(config);
            this.setField(this.getRecord().getField('Owner'));
            this.callParent(arguments);
        },
        _drawEditMode: function () {
            var cls = 'owner-meta-field';

            this.editor = this._getOwnerEditor();
            if (!this.editor.editable && !this._hasOwner(this.getRecord().data)) {
                this.editor.emptyText = '-- No Owner --';

            } else {
                this.ownerImage = Ext.create('Ext.Component', {
                    cls: 'detail-owner-image',
                    html: '<img src="' + this._getProfileImageSrc(this.getRecord().data) + '">'
                });
                cls += ' has-owner-img';
            }

            this.add({
                xtype: 'container',
                layout: 'hbox',
                cls: cls,
                items: [
                    this.ownerImage,
                    this.editor
                ]
            });
        },
        _getOwnerEditor: function () {
            var editor = Rally.ui.detail.view.DetailEditorFactory.getEditor(this.getField(), this.getRecord());
            editor.width = 240;
            editor.on('setvalue', this._updateOwnerImage, this);
            editor.on('expand', function() {
                this.suspendEvent('fieldchanged');
                this.el.down('input').dom.value = "";
            }, this);
            editor.on('collapse', function() {
                this.resumeEvent('fieldchanged');
            }, this);
            editor.on('focus', function() {
                editor.expand();
            }, this);

            return editor;
        },
        _updateOwnerImage: function() {
            var imgEl = this.getEl().down('img');

            if (imgEl) {
                imgEl.set({'src': this._getProfileImageSrc(this.getRecord().data)});
            }
        },
        _getProfileImageSrc: function (recordData) {
            var OWNER_IMAGE_SIZE = 31;
            return this._hasOwner(recordData) ? Rally.util.User.getProfileImageUrl(OWNER_IMAGE_SIZE, recordData.Owner) :
                Rally.util.User.getNoOwnerImageUrl();
        },
        _hasOwner: function(recordData) {
            return  _.isEmpty(recordData.Owner) === false;
        },
        getSubmitData: function () {
            return {
                Owner: this.editor.getValue()
            };
        }
    });
})();