// BEGIN FLOCK GPL
//
// Copyright Flock Inc. 2005-2009
// http://flock.com
//
// This file may be used under the terms of the
// GNU General Public License Version 2 or later (the "GPL"),
// http://www.gnu.org/licenses/gpl.html
//
// 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.
//
// END FLOCK GPL

const CC = Components.classes;
const CI = Components.interfaces;
const CU = Components.utils;
const CR = Components.results;

CU.import("resource:///modules/FlockXPCOMUtils.jsm");
CU.import("resource:///modules/FlockStringBundleHelpers.jsm");

const MT_CONTRACTID = "@flock.com/migrate-toolbars;1";
const MT_CLASSID    = Components.ID("{bad50645-93f2-4f3f-9323-dc54d901ed4b}");
const MT_CLASSNAME  = "Flock Toolbars Migration";

const DIR_SERVICE_CONTRACTID = "@mozilla.org/file/directory_service;1";

/*************************************************************************
 * Component: flockMigrateToolbars
 *************************************************************************/

function flockMigrateToolbars() {
}

/*************************************************************************
 * flockMigrateToolbars: XPCOM Component Creation
 *************************************************************************/

flockMigrateToolbars.prototype = new FlockXPCOMUtils.genericComponent(
  MT_CLASSNAME,
  MT_CLASSID,
  MT_CONTRACTID,
  flockMigrateToolbars,
  CI.nsIClassInfo.SINGLETON,
  [
    CI.flockIMigratable
  ]
);

flockMigrateToolbars.prototype._xpcom_categories = [
  { category: "flockMigratable" }
];

/*************************************************************************
 * flockMigrateToolbars: private members
 *************************************************************************/

flockMigrateToolbars.prototype._init =
function flockMigrateToolbars__init() {
  this._logger = CC['@flock.com/logger;1'].createInstance(CI.flockILogger);
  this._logger.init("migrateToolbars");
};

// delete localstore.rdf to reset toolbars.
flockMigrateToolbars.prototype._resetToolbars =
function flockMigrateToolbars__resetToolbars() {
  var directoryService = CC[DIR_SERVICE_CONTRACTID]
                         .getService(CI.nsIProperties);
  var localstoreFile = directoryService.get("LStoreS", CI.nsIFile);
  if (localstoreFile.exists()) {
    localstoreFile.remove(false);
  }
};

flockMigrateToolbars.prototype._mungeToolbars =
function flockMigrateToolbars__mungeToolbars(aOldVer) {
  const RDFS = CC["@mozilla.org/rdf/rdf-service;1"]
               .getService(CI.nsIRDFService);
  var ds = RDFS.GetDataSource("rdf:local-store");
  var currentset = RDFS.GetResource("currentset");

  // Remove the feedback and help buttons
  var node = RDFS.GetResource("chrome://browser/content/browser.xul#nav-bar");
  var navbar = ds.GetTarget(node, currentset, true);
  if (navbar && navbar instanceof CI.nsIRDFLiteral) {
    var currentNavBar = navbar.Value;
    var newNavBar = currentNavBar.replace("feedback-button", "")
                                 .replace("help-button", "")
                                 .replace(/,,+/g, ",")
                                 .replace(/,$/, "");

    if (currentNavBar != newNavBar) {
      ds.Change(node, currentset, navbar, RDFS.GetLiteral(newNavBar));
    }
  }

  // Add the People and Webmail buttons to the Flock Bar
  node = RDFS.GetResource("chrome://browser/content/browser.xul#PersonalToolbar");
  var flockBar = ds.GetTarget(node, currentset, true);
  if (flockBar && flockBar instanceof CI.nsIRDFLiteral) {
    var currentFlockBar = flockBar.Value;
    var newFlockBar = currentFlockBar;
    if (currentFlockBar.length == 0) { 
      if (aOldVer == "0.9") {
        newFlockBar = "people-button,webmail-button";
      } else {
        newFlockBar = "webmail-button";
      }
    } else {
      if (newFlockBar.indexOf("webmail-button") == -1) {
        if (newFlockBar.indexOf("news-button,separator") != -1) {
          newFlockBar = newFlockBar.replace("news-button,separator",
                                            "news-button,webmail-button,separator");
        } else if (newFlockBar.indexOf("news-button") != -1) {
          newFlockBar = newFlockBar.replace("news-button",
                                            "news-button,webmail-button,separator");
        } else {
          newFlockBar = "webmail-button," + newFlockBar;
        }
      }
      if (aOldVer == "0.9") {
        if (currentFlockBar.indexOf("people-button") == -1) {
          if (currentFlockBar.indexOf("my-world-button,separator") != -1) {
            newFlockBar = newFlockBar.replace("my-world-button,separator",
                                              "$&,people-button");
          } else if (newFlockBar.indexOf("my-world-button") != -1) {
            newFlockBar = newFlockBar.replace("my-world-button",
                                              "$&,separator,people-button");
          } else {
            newFlockBar = "people-button," + newFlockBar;
          }
        }
      }
    }

    if (currentFlockBar != newFlockBar) {
      ds.Change(node, currentset, flockBar, RDFS.GetLiteral(newFlockBar));
    }
  }

  // Make sure the Flock Bar is visible
  var collapsed = RDFS.GetResource("collapsed");
  var target = ds.GetTarget(node, collapsed, true);
  if (target) {
    ds.Unassert(node, collapsed, target);
  }
};

flockMigrateToolbars.prototype._migrateSidebar =
function flockMigrateToolbars__migrateSidebar(aOldVer) {
  const RDFS = CC["@mozilla.org/rdf/rdf-service;1"]
               .getService(CI.nsIRDFService);
  var ds = RDFS.GetDataSource("rdf:local-store");

  var node = RDFS.GetResource("chrome://browser/content/browser.xul#sidebar-box");
  var srcRes = RDFS.GetResource("src");
  var sidebar = ds.GetTarget(node, srcRes, true);
  if (sidebar &&
      sidebar instanceof CI.nsIRDFLiteral)
  {
    var currentSidebar = sidebar.Value;
    var newSidebar = "chrome://flock/content/services/common/accountsSidebar.xul"

    if (currentSidebar.match("accountsSidebar.xul") &&
        currentSidebar != newSidebar)
    {
      ds.Change(node, srcRes, sidebar, RDFS.GetLiteral(newSidebar));
    }
  }

}

/*************************************************************************
 * flockMigrateToolbars: flockIMigratable implementation
 *************************************************************************/

flockMigrateToolbars.prototype.__defineGetter__("migrationName",
function flockMigrateToolbars_getter_migrationName() {
  return flockGetString("common/migrationNames", "migration.name.toolbars");
});

flockMigrateToolbars.prototype.needsMigration =
function flockMigrateToolbars_needsMigration(aOldVersion) {
  this._init();
  this._logger.debug(".needsMigration('" + aOldVersion + "')");

  if ((aOldVersion.substr(0, 3) == "0.5") ||
      (aOldVersion.substr(0, 3) == "0.7") ||
      (aOldVersion.substr(0, 3) == "0.9") ||
      (aOldVersion.substr(0, 3) == "1.0") ||
      (aOldVersion.substr(0, 3) == "1.1") ||
      (aOldVersion.substr(0, 3) == "1.2") ||
      (aOldVersion.substr(0, 4) == "2.0b"))
  {
    return true;
  } else {
    return false;
  }
};

flockMigrateToolbars.prototype.startMigration =
function flockMigrateToolbars_startMigration(aOldVersion, aFlockMigrationProgressListener) {
  this._logger.debug(".startMigration('"
                     + aOldVersion
                     + "', 'aFlockMigrationProgressListener')");


  var ctxt = {
    oldVersion: aOldVersion,
    listener: aFlockMigrationProgressListener
  };

  ctxt.listener.onUpdate(0, "Migrating toolbars");
  return {
    wrappedJSObject: ctxt
  };
};

flockMigrateToolbars.prototype.finishMigration =
function flockMigrateToolbars_finishMigration(ctxtWrapper) {
};

flockMigrateToolbars.prototype.doMigrationWork =
function flockMigrateToolbars_doMigrationWork(ctxtWrapper) {
  var ctxt = ctxtWrapper.wrappedJSObject;

  // only do the following when migrating from 0.7.x (Cardinal)
  if ((ctxt.oldVersion.substr(0, 3) == "0.7") ||
      (ctxt.oldVersion.substr(0, 3) == "0.5"))
  {
    // reset toolbars during migration as a lot has changed.
    this._resetToolbars();
  } else if ((ctxt.oldVersion.substr(0, 3) == "0.9") ||
             (ctxt.oldVersion.substr(0, 3) == "1.0") ||
             (ctxt.oldVersion.substr(0, 3) == "1.1") ||
             (ctxt.oldVersion.substr(0, 4) == "2.0b"))
  {
    this._mungeToolbars(ctxt.oldVersion.substr(0, 3));
    this._migrateSidebar(ctxt.oldVersion.substr(0, 3));
  } else if (ctxt.oldVersion.substr(0, 3) == "1.2") {
    this._migrateSidebar(ctxt.oldVersion.substr(0, 3));
  }

  return false;
};

/*************************************************************************
 * XPCOM Support - Module Construction
 *************************************************************************/

// Create array of components.
var componentsArray = [flockMigrateToolbars];

// Generate a module for XPCOM to find.
var NSGetModule = FlockXPCOMUtils.generateNSGetModule(MT_CLASSNAME,
                                                      componentsArray);
