/*
 * 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 */
/*global define: true, graphite: true*/

define(['jquery', 'parfait/ImageUtil'], function ($, ImageUtil) {
    'use strict';
    var DwImageUtil = $.extend(ImageUtil, {
        saveCanvasAsImage: function (canvasRef, imageFormat, imageQuality, fillColor) {
            
            var finalCanvas = canvasRef;
            var result      = null;
            
            if (canvasRef) {
                
                // In case of jpgs or jpegs let's fill the color
                // with white, draw our layer canvas contents onto that and
                // export the contents from the new canvas element. Canvas by
                // default replaces transparency with black color, in case of
                // exporting it's content as jpg.
                
                if (imageFormat === 'jpg' || imageFormat === 'jpeg') {

                    var destinationCanvas    = document.createElement("canvas");
                    destinationCanvas.width  = canvasRef.width;
                    destinationCanvas.height = canvasRef.height;

                    var destCtx = destinationCanvas.getContext('2d');

                    //fill the destination canvas with fill color white.
                    destCtx.fillStyle = fillColor;
                    destCtx.fillRect(0, 0, canvasRef.width, canvasRef.height);

                    //draw the original canvas onto the destination canvas
                    destCtx.drawImage(canvasRef, 0, 0);
                    finalCanvas = destinationCanvas;
                }

                result = finalCanvas.toDataURL('image/' + imageFormat, imageQuality);
            }
            
            return result;
        }
    });
    
    return DwImageUtil;
});