/*
 * Copyright (c) OutWit Technologies 2007-2020
 * All rights reserved.
 */

/**
 * @fileOverview Download.
 * Mostly stolen from the great fireOne!
 *
 * @robber vn
 * @version 0.8
 */



let Cu = Components.utils;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");

outwitHub.gDownloadMgr = null;

setTimeout(function() {
  outwitHub.gDownloadMgr = Components.classes["@mozilla.org/download-manager;1"]
                .getService(Components.interfaces.nsIDownloadManager);
  outwitHub.DownloadMonitorPanel.init();
}, 4000);



function BrowserDownloadsUI(){
  Components.classes["@mozilla.org/download-manager-ui;1"]
  .getService(Components.interfaces.nsIDownloadManagerUI).show(window);
}


outwitHub.DownloadMonitorPanel = {
   _panel: null,
  _activeStr: null,
  _pausedStr: null,
  _lastTime: Infinity,
  _listening: false,

  init: function() {
    Cu.import("resource://gre/modules/DownloadUtils.jsm");
    Cu.import("resource://gre/modules/PluralForm.jsm");
    this._panel = document.getElementById("download-monitor");
    this._activeStr = coreKit.localeService.getString('downloadActiveStr','chrome://outwit-modules/locale/localize.properties'),
    this._pausedStr = coreKit.localeService.getString('downloadPauseStr','chrome://outwit-modules/locale/localize.properties'),

    outwitHub.gDownloadMgr.addListener(this);
    this._listening = true;
    this.updateStatus();
  },

  uninit: function() {
    if (this._listening)
      outwitHub.gDownloadMgr.removeListener(this);
  },

  /**
   * Update status based on the number of active and paused downloads
  */
  updateStatus: function() {
    let numActive = outwitHub.gDownloadMgr.activeDownloadCount;
    // Hide the panel and reset the "last time" if there's no downloads
    if (numActive == 0) {
      this._panel.hidden = true;
      this._lastTime = Infinity;
      return;
    }

    //Find the download with the longest remaining time
    let numPaused = 0;
    let maxTime = -Infinity;
    let dls = outwitHub.gDownloadMgr.activeDownloads;
    while (dls.hasMoreElements()) {
      let dl = dls.getNext().QueryInterface(Components.interfaces.nsIDownload);
      if (dl.state == outwitHub.gDownloadMgr.DOWNLOAD_DOWNLOADING) {
        // Figure out if this download takes longer
        if (dl.speed > 0 && dl.size > 0)
          maxTime = Math.max(maxTime, (dl.size - dl.amountTransferred) / dl.speed);
        else
          maxTime = -1;
        }
        else if (dl.state == outwitHub.gDownloadMgr.DOWNLOAD_PAUSED)
          numPaused++;
        }

        // Get the remaining time string and last sec for time estimation
        let timeLeft;
        [timeLeft, this._lastTime] = DownloadUtils.getTimeLeft(maxTime, this._lastTime);
        // Figure out how many downloads are currently downloading
        let numDls = numActive - numPaused;
        let status = this._activeStr;
        // If all downloads are paused, show the paused message instead
        if (numDls == 0) {
          numDls = numPaused;
          status = this._pausedStr;
        }
        // Get the correct plural form and insert the number of downloads and time
        // left message if necessary
        status = PluralForm.get(numDls, status);
        status = status.replace("#1", numDls);
        status = status.replace("#2", timeLeft);
        // Update the panel and show it
        this._panel.label = status;
        this._panel.hidden = false;
      },

      //// nsIDownloadProgressListener
     /**
       * Update status for download progress changes
       */
    onProgressChange: function() {
      this.updateStatus();
    },

    /**
     * Update status for download state changes
     */
    onDownloadStateChange: function() {
      this.updateStatus();
    },

    onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus, aDownload) {},

    onSecurityChange: function(aWebProgress, aRequest, aState, aDownload) {},

    //// nsISupports
    QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsIDownloadProgressListener]),
};

