/**
 * @constructor
 * @class ArtworkUploader
 */
ArtworkUploader = new JS.Class(/** @scope ArtworkUploader.prototype */{
    include: Ojay.Observable,
    
    extend: /** @scope ArtworkUploader */{
        
        REMOVE_URI: '/blank.html?action=com.othermedia.royalacademy.summerexhibition.actions.' +
                    'SummerExhibitionRemoveImageAction.doDefault',
                    
        UPDATE_URI: '/blank.html?action=com.othermedia.royalacademy.summerexhibition.actions.' +
                    'SummerExhibitionUploadImageAction.doGetImageExists',
        /**
         * @param {HTMLElement} form
         * @param {String} name
         */
        getInputs: function(form, name) {
            return Ojay(form).descendants('input,textarea,select').filter(function(input) {
                return input.node.name === name;
            });
        },
        
        /**
         * @param {ArtworkUploader} uploader
         */
        cache: function(uploader) {
            this._instances[uploader.getIdString()] = uploader;
            var formId = uploader.getFormId();
            this._forms[formId] = this._forms[formId] || [];
            this._forms[formId].push(uploader);
        },
        
        /**
         * @param {String} id
         * @returns {ArtworkUploader}
         */
        find: function(id) {
            return this._instances[id] || null;
        },
        
        /**
         * @param {String} id
         * @returns {ArtworkUploader}
         */
        findByForm: function(id) {
            var forms = this._forms[id];
            return forms ? forms.slice() : [];
        },
        
        /**
         * @param {Object} data
         */
        uploadComplete: function(data) {
            var id = data.formId + '/' + data.fieldName,
                instance = this.find(id);
            if (!instance) return;
            instance.notify(data);
        },
        
        _instances: {},
        _forms: {},
        
        FORM_ID_FIELD:  'formId',
        NAME_FIELD:     'fieldName',
        PREVIEW_CLASS:  'image-preview'
    },
    
    /**
     * @param {HTMLElement} form
     */
    initialize: function(form) {
        this._form = Ojay(form);
        
        this._linkedFormId = this.klass.getInputs(this._form, this.klass.FORM_ID_FIELD).node.value;
        this._linkedFieldName = this.klass.getInputs(this._form, this.klass.NAME_FIELD).node.value;
        this.klass.cache(this);
        
        this._preview = this._form.descendants('.' + this.klass.PREVIEW_CLASS);
        this._removeButton = this._form.descendants('.remove');
        this._submitButton = this._form.descendants('input.submit');
        this._removeButton.on('click', Ojay.stopDefault)._(this).remove();
        
        this.update();
    },
    
    /**
     * @returns {String}
     */
    getFormId: function() {
        return this._linkedFormId;
    },
    
    /**
     * @returns {HTMLElement}
     */
    getSubmissionForm: function() {
        this.link();
        return this._submissionForm;
    },
    
    /**
     * @returns {String}
     */
    getIdString: function() {
        return this._linkedFormId + '/' + this._linkedFieldName;
    },
    
    /**
     * @returns {ArtworkUploader}
     */
    link: function() {
        this._submissionForm = Ojay.byId(this.getFormId());
        return this;
    },
    
    /**
     * @param {Object} data
     */
    notify: function(data) {
        var content = data.errors
                ? Ojay.HTML.ul(function(HTML) { [].map.call(data.errors, HTML.method('li')) })
                : Ojay.HTML.img({src: data.imageSrc});
        this._hasImage = !!data.imageSrc;
        this._preview.setContent(content);
        if(data.imageSrc){
	        this._submitButton.addClass('remove');
	        this._removeButton.removeClass('remove');
	    }
    },
    
    /**
     * @returns {Boolean}
     */
    hasImage: function() {
        return !!this._hasImage;
    },
    
    /**
     */
    update: function() {
        Ojay.HTTP.GET(this.klass.UPDATE_URI, {imageRef: this._linkedFieldName}, {
            onSuccess: function(response) {
                var data = response.parseJSON();
                if (data.imageSrc) this.notify(data);
            }.bind(this)
        });
    },
    
    /**
     */
    remove: function() {
        Ojay.HTTP.POST(this.klass.REMOVE_URI, {image: this._linkedFieldName}, {
            onSuccess: function() {
                this._hasImage = false;
                this._preview.setContent('');
                this._submitButton.removeClass('remove');
        		this._removeButton.addClass('remove');
            }.bind(this)
        });
    }
});
