
/*
 * ADOBE CONFIDENTIAL
 *
 * Copyright (c) 2013-2014 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, nomen: true, indent: 4 */
/*global define: true */

define([
    "jquery",
    "underscore",
    "backbone"
], function ($, _, Backbone) {
    "use strict";

    var DwCacheController = Backbone.Model.extend({
        mostRecentlyUsedMD5: [],
        maxCachedPSDs: 50,
        
        initializeCache: function () {
            window.graphite.events.on('psd-processed', this.updateCacheOnPSDAccess, this);
            var self = this;
            
            $.ajax({
                url:        this.getCacheManifestPath(),
                async:      true,
                cache:		false,
                contentType: 'application/json',
                dataType:   'json',
                success:    function (fileData, status) {
                    self.mostRecentlyUsedMD5 = _(fileData).toArray();
                }
            });
        },
        
        getCacheManifestPath: function () {
            var path = window.dwData ? window.dwData.configPath : "";
            path = path + 'files/cacheManifest.json';
            return path;
        },
        
        updateCacheOnPSDAccess: function (md5) {
            if (md5 === 'WelcomeExp') {
                return;
            }
            var fromIndex = this.mostRecentlyUsedMD5.indexOf(md5),
                toIndex = 0;
            if (fromIndex >= 0) {
                this.arrayMove(fromIndex, toIndex);
            } else {
                this.mostRecentlyUsedMD5.splice(0, 0, md5);
                if (this.mostRecentlyUsedMD5.length > this.maxCachedPSDs) {
                    this.mostRecentlyUsedMD5.pop();
                }
            }
            this.updateCacheOnDisk();
        },

        updateCacheOnDisk: function () {
            var jsonString = JSON.stringify(this.mostRecentlyUsedMD5),
                path = this.getCacheManifestPath();
            
            window.dwPSDExtractManager.writeString(path, jsonString, null);
        },
        
        arrayMove: function (fromIndex, toIndex) {
	        this.mostRecentlyUsedMD5.splice(toIndex, 0, this.mostRecentlyUsedMD5.splice(fromIndex, 1)[0]);
        }
        
    });

    return new DwCacheController();
});