/*
 * ADOBE CONFIDENTIAL
 *
 * Copyright (c) 2015 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, node:true */
/*global require: true, $: true, exports: true, csInterface: true*/

(function () {
    "use strict";

    var MaxPixels = function () {};

    MaxPixels.prototype = {
        /**
         * Node.js has a default memory limit of 512MB on 32-bit machines and 1024MB on 64-bit machines.
         * It was empirically determined that a 10k x 10k (100M pixel image) uses ~580MB of memory in an IPC-connected
         * generator. We'll use that value for 64-bit machines and 5k x 5k (25M pixel image) for 32-bit machines, to be
         * conservative.
         *
         * NOTE: Do not use this from CEP. process.arch returns whether CEP is 32-bit or not instead of whether the
         * machine is 32-bit or not.
         *
         * TODO: When we change generator to a streaming implementation, we shouldn't be limited by memory anymore.
         */
        getMaxPixels: function() {
            return (process.arch === "x64" ? 100 : 25) * 1000 * 1000;
        },
        getMaxScaleFactor: function (originalDimensions, maxPixels) {
            maxPixels = maxPixels || this.getMaxPixels();
            var maxScaleFactor = Math.sqrt(maxPixels / (Math.ceil(originalDimensions.width) * Math.ceil(originalDimensions.height)));
            return this._roundDown(maxScaleFactor, 100);
        },
        getMaxDimensions: function (originalDimensions, maxPixels) {
            var maxScaleFactor = this.getMaxScaleFactor(originalDimensions, maxPixels);
            return {
                width: Math.floor(Math.ceil(originalDimensions.width) * maxScaleFactor),
                height: Math.floor(Math.ceil(originalDimensions.height) * maxScaleFactor)
            };
        },
        _roundDown: function (value, placeInTens) {
            return Math.floor(value * placeInTens) / placeInTens;
        }
    };

    module.exports = new MaxPixels();
}());
