/* ***** BEGIN LICENSE BLOCK *****
Version: MPL 1.1/GPL 2.0/LGPL 2.1

The contents of this file are subject to the Mozilla Public License Version
1.1 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/

Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the
License.

The Original Code is Organize Search Engines.

The Initial Developer of the Original Code is
Malte Kraus.
Portions created by the Initial Developer are Copyright (C) 2007-2009
the Initial Developer. All Rights Reserved.

Contributor(s):
  Malte Kraus <mails@maltekraus.de> (Original author)

 Alternatively, the contents of this file may be used under the terms of
 either the GNU General Public License Version 2 or later (the "GPL"), or
 the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 in which case the provisions of the GPL or the LGPL are applicable instead
 of those above. If you wish to allow use of your version of this file only
 under the terms of either the GPL or the LGPL, and not to allow others to
 use your version of this file under the terms of the MPL, indicate your
 decision by deleting the provisions above and replace them with the notice
 and other provisions required by the GPL or the LGPL. If you do not delete
 the provisions above, a recipient may use your version of this file under
 the terms of any one of the MPL, the GPL or the LGPL.
***** END LICENSE BLOCK ***** */

/* The class arranges the provided images in two rows in the provided dimensions.
   It will do both upscale and downscale the images when neccessary. If the
   number of images is odd, the image of biggest height (then width, then order)
   will be the last image in doubled height.

example usage:
      var image1 = "data:image/x-icon;base64, ";
      var image2 = makeURI("data:image/x-icon;base64, ");
      var image3 = new Image("http://www.google.de/images/firefox/google.gif");
      var resizer = new Resizer(24, 16, image1, image2, image3);
      resizer.onload = function() {
        resizer.paintIcons();
        // do something more useful!
        prompt("URI:", resizer.getDataURL());
      };
      resizer.addIconByURL("data:image/x-icon;base64, ");
      window.setTimeout(function() {
          resizer.addIconByURL("data:image/x-icon;base64, ");
          resizer.addIconByURL("data:image/x-icon;base64, ");
          resizer.addIconByImage(document.getElementsByTagName("img")[0]);
      }, 1500);
*/

Components.utils.import("resource://gre/modules/Services.jsm");
var EXPORTED_SYMBOLS = ["Resizer"];

var Resizer = function Resizer(width, height) {
  this.width = width;
  this.height = height;
  this._loading = [];
  this.icons = [];

  for(var i = 2; i < arguments.length; i++) {
    if(arguments[i] instanceof HTMLImageElement || arguments[i] instanceof Image ||
       arguments[i] instanceof HTMLCanvasElement ||
       (arguments[i] instanceof XULElement && arguments[i].nodeName == "image"))
      this.addIconByImage(arguments[i]);
    else if(arguments[i] instanceof Ci.nsIURI)
      this.addIconByURL(arguments[i].spec);
    else
      this.addIconByURL(arguments[i]);
  }
};
Resizer.prototype = {
  width: 0,
  height: 0,
  icons: null,
  __canvas: null,
  get _canvas() {
    if(!this.__canvas)
      this.__canvas = this._createCanvas();
    return this.__canvas;
  },
  __document: null,
  get _document() {
    if(!this.__document)
      this.__document = Services.wm.getMostRecentWindow("navigator:browser").document;
    return this.__document;
  },
  _createCanvas: function() {
    var canvas = this._document.createElementNS("http://www.w3.org/1999/xhtml",
                                                "canvas");
    canvas.setAttribute("width", this.width);
    canvas.setAttribute("height", this.height);
    return canvas.getContext("2d");
  },
  onload: null,

  get loaded() {
    return !this._loading.length;
  },
  _loading: null,

  _iconAdded: function(icon) {
    icon.squarePixels = (icon.naturalWidth * icon.naturalHeight);
    if(this.loaded && this.onload) {
      this.onload.call(this, icon);
    }
  },
  // moves the biggest (in height) image to the end as this may have doubled height in the end
  _reorder: function() {
    var icons = this.icons;
    if(icons.length < 2)
      return;

    var biggest = icons.length - 1; // pick one
    for(var i = 0; i < icons.length - 1; i++) {
      if(icons[i].height > icons[biggest].height ||
         (icons[i].height == icons[biggest].height && icons[i].width <= icons[biggest].width)) {
        biggest = i;
      }
    }
    if(biggest + 1 != icons.length) {
      var image = icons[biggest];
      this.icons = icons.slice(0, biggest).concat(icons.slice(biggest + 1));
      this.icons.push(image);
    }
  },

  _addLoadingIcon: function(img) {
    this._loading.push(img);
    var This = this;
    img.addEventListener("load", function() {
      This.icons.push(img);
      var idx = This._loading.indexOf(img);
      if(idx != -1) {
        This._loading.splice(idx, 1);
      }
      This._iconAdded(img);
    }, false);
  },
  addIconByURL: function(url) {
    var img = new this._document.defaultView.Image();
    this._addLoadingIcon(img);
    img.src = url;
  },
  removeIconByURL: function(url) {
    for(var i = this.icons.length; i > -1; i--) {
      if(this.icons[i].src == url)
        this.removeIconByImage(this.icons[i]);
    }
  },
  addIconByImage: function(img) {
    if(!img.naturalWidth && !img.getContext) { // not loaded yet
      this._addLoadingIcon(img);
    } else {
      this.icons.push(img);
      this._iconAdded(img);
    }
  },
  removeIconByImage: function(img) {
    var idx;
    while((idx = this.icons.indexOf(img)) != -1)
      this.icons.splice(idx, 1);
  },

  paintIcons: function() {
    var canvas = this._canvas;
    canvas.fillStyle = canvas.strokeStyle = "rgba(0,0,0,0)"; // transparent
    canvas.clearRect(0, 0, this.width, this.height);
    var num = this.icons.length;
    if(!num) return;
    var height = Math.floor(this.height / 2);
    var width = (this.width * this.height) / ((num + (num % 2)) * height);

    if(num % 2)
      this._reorder();

    for(var i = 0; i + 1 < num; i++) {
      canvas.drawImage(this.icons[i], Math.floor(i / 2) * width,
                       (i % 2) * height, width, height);
    }

    // draw the last icon in doubled height if necessary
    canvas.drawImage(this.icons[i], Math.floor(i / 2) * width, (i % 2) * height,
                     width, height * ((num % 2) + 1));
  },
  getDataURL: function() {
    return this._canvas.canvas.toDataURL();
  }
};
