/*
 * ADOBE CONFIDENTIAL
 *
 * Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Adobe Systems Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Adobe Systems Incorporated and its
 * suppliers and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Adobe Systems Incorporated.
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, bitwise: true */
/*global graphite*/

define([
    'underscore',
    'backbone',
    'plugin-dependencies',
    'ccweb.files.extract/models/PSDModel',
    'ccweb.files.extract/Constants'
], function (_, Backbone, deps, PSDModel, Constants) {
    'use strict';
    var AssetController = Backbone.Model.extend({
        getAsset: function (assetId, layerCompId, successCallback, errorCallback, context) {
            var localContent = context ? context.localContent : false,
                psdModel = new PSDModel({id: assetId, assetId: assetId, layerCompId: layerCompId, localContent: localContent}),
                errorCallbackWrapper = function (response, err) {
                    var status = response.status;
                    if (err) {
                        if (err.errorCode === Constants.WorkerErrorCodes.GRAPHITE_REJECTED) {
                            status = 422; // 'Unprocessable entity' was the nearest I could find :-)
                        }
                        if (err.errorCode === Constants.WorkerErrorCodes.GRAPHITE_PROCESSING) {
                            status = 500;
                        }
                    }
                    if (status >= 300) {
                        psdModel.set('errorInfo', err);
                        psdModel.set('status', status);
                    }
                    errorCallback.apply(context, [response, err]);
                };

            if (deps.utils.hasFeature('extract_split_load')) {
                graphite.serverAPI.loadPsdModel2(psdModel, successCallback, errorCallbackWrapper, context);
            } else {
                if (localContent) {
                    graphite.serverAPI.loadPsdModelFromUrl(psdModel, context.localContent.directory + '/graphite.json', successCallback, errorCallbackWrapper, context);
                } else {
                    graphite.serverAPI.loadPsdModel(psdModel, successCallback, errorCallbackWrapper, context);
                }
            }

            return psdModel;
        }

    });

    return new AssetController();
});
