if (typeof yndenz === 'undefined') {
    var yndenz = yndenz || function () {
        return {};
    };
}

yndenz.plugins = yndenz.plugins || function () {
    return {};
};

yndenz.plugins.optimizeImages = yndenz.plugins.optimizeImages || function () {
    return {};
};

yndenz.plugins.optimizeImages.file = function (details) {
    this.target = null;
    this.details = details;

    this.draw();
};

yndenz.plugins.optimizeImages.file.prototype.draw = function () {
    if (this.target === null) {
        this.target = jQuery('<div/>').addClass('yp-optimize-images__list-item');
        this.target.addClass('status-' + this.details.status);
        jQuery('.yp-optimize-images__list').prepend(jQuery('<li/>').append(this.target));
    } else {
        this.target.html('');
    }

    var id = jQuery('<div/>').addClass('yp-optimize-images__list-item-id');
    id.append(this.details.id);
    this.target.append(id);

    var filename = jQuery('<div/>').addClass('yp-optimize-images__list-item-filename');
    filename.append(this.details.filename);
    this.target.append(filename);

    var status = jQuery('<div/>').addClass('yp-optimize-images__list-item-status');
    var statusIcon = jQuery('<i/>').addClass('fa');
    switch (this.details.status) {
        case 'done':
            statusIcon.addClass('fa-check');
            break;
        case 'processing':
            statusIcon.addClass('fa-cogs');
            break;
        case 'pending':
            statusIcon.addClass('fa-clock-o');
            break;
        case 'failed':
            statusIcon.addClass('fa-exclamation-triangle');
            break;
        default:
            statusIcon.addClass('fa-question');
            break;
    }
    status.append(statusIcon);
    this.target.append(status);
};

yndenz.plugins.optimizeImages.file.prototype.getStatus = function () {
    return this.details.status;
};

yndenz.plugins.optimizeImages.file.prototype.setStatusProcessing = function () {
    this.details.status = 'processing';
    this.draw();
};

yndenz.plugins.optimizeImages.file.prototype.checkStatus = function (response, status) {
    if (status === 'success') {
        this.details.status = response.responseJSON.status;
    } else {
        this.details.status = 'failed';
    }
    this.draw();
};

yndenz.plugins.optimizeImages.file.prototype.process = function () {
    this.details.status = 'processing';
    return jQuery.ajax({
        url: ajaxurl,
        data: {action: 'optimize_images_optimize', id: this.details.id},
        beforeSend: jQuery.proxy(this.setStatusProcessing, this),
        complete: jQuery.proxy(this.checkStatus, this)
    });
};