dojo.provide("parus.progressDialog");

dojo.require("dijit.Dialog");
dojo.require("dijit.form.Button");
dojo.require("dijit.ProgressBar");

dojo.require("parus.parus8");
dojo.require("parus.dialog");

dojo.declare("parus.progressDialog", [parus.messageDialog], {

  max: null,

  _value: null,

  postCreate: function() {
    this.inherited(arguments);
    this.dialog.closeButtonNode.style.display = "none";
    if (this.max) this.setMax(this.max);
  },

  setMax: function(max) {
    this.max = max;
    if (this.max) {
      this.bar.attr("indeterminate", false);
      this.bar.attr("maximum", this.max);
      this.bar.attr("value", 0);
      this._value = 0;
    }
  },

  step: function() {
    this._value++;
    this.bar.attr("value", this._value);
  }

});

dojo.mixin(parus.progressDialog, {

  iterateOverGrid: function(label, grid, itemProc, doneProc) {
    var store = grid.store;
    var item = grid.selection.getFirstSelected();
    var items = [];

    for (var i = 0; i < grid.selection.getSelectedCount(); i++) {
      items.push(item);
      item = grid.selection.getNextSelected(item);
    };

    parus.progressDialog.iterateOverArray(label, items, itemProc, doneProc);
  },

  iterateOverArray: function(label, items, itemProc, doneProc) {
    var progressIndicator = new parus.progressDialog({
      message: label,
      max: items.length
    });
    progressIndicator.show();

    var localitems = dojo.clone(items);

    var f = function() {
      var item = localitems.shift();
      if (item) {
        try {
          itemProc(item);
        } catch (e) {
          progressIndicator.step();
          setTimeout(f, 50);
          throw e;
        }
        progressIndicator.step();
        setTimeout(f, 50);
      }
      else {
        progressIndicator.close();
        progressIndicator.destroyRecursive();
        if (doneProc) doneProc();
      }
    };

    setTimeout(f, 50);

  }

});