// BEGIN FLOCK GPL
//
// Copyright Flock Inc. 2005-2008
// 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 ENABLE_DEBUG = true; // switch to turn off slow debug code for production
function DEBUG(x) { if (ENABLE_DEBUG) debug("flockBlogsomeService: "+x+"\n"); }

const Cc = Components.classes;
const Ci = Components.interfaces;

const BLOGSOME_CID = Components.ID('{c36e232f-9a3e-4848-b9a8-d7a880a7544f}');
const BLOGSOME_CONTRACTID = '@flock.com/service/blogsome;1';

const BLOGSOME_FAVICON = 'http://www.blogsome.com/favicon.ico';
const SERVICE_ENABLED_PREF          = "flock.service.blogsome.enabled";
const CATEGORY_COMPONENT_NAME       = "Blogsome JS Component"
const CATEGORY_ENTRY_NAME           = "blogsome"

const RDFS = Cc['@mozilla.org/rdf/rdf-service;1'].getService (Ci.nsIRDFService);

var gCompTK;
function getCompTK() {
  if (!gCompTK) {
    gCompTK = Components.classes["@flock.com/singleton;1"]
                        .getService(Components.interfaces.flockISingleton)
                        .getSingleton("chrome://browser/content/flock/services/common/load-compTK.js")
                        .wrappedJSObject;
  }
  return gCompTK;
}

function loadSubScript(spec) {
  var loader = Cc['@mozilla.org/moz/jssubscript-loader;1'].getService(Ci.mozIJSSubScriptLoader);
  var context = {};
  loader.loadSubScript(spec, context);
  return context;
}

var loader = Cc['@mozilla.org/moz/jssubscript-loader;1'].getService(Ci.mozIJSSubScriptLoader);

loader.loadSubScript('chrome://browser/content/utilityOverlay.js');
loader.loadSubScript("chrome://flock/content/xmlrpc/xmlrpchelper.js");
loader.loadSubScript("chrome://flock/content/blog/blogBackendLib.js");


function userBlogsListener(aListener){
  this.listener = aListener;
}

userBlogsListener.prototype =
{
  // aResult is an Array (simpleEnumerator) of struct objects
  onResult: function(aResult) {
    var result = new Array();
    for (i=0; i<aResult.length; i++){
      var entry = aResult[i];
      var newAccount = new BlogAccount(entry.blogName);
      newAccount.blogid = entry.blogid;
      newAccount.apiLink = "";
      newAccount.URL = entry.url;
      result.push(newAccount);
    }
    this.listener.onResult(new simpleEnumerator(result));
  },
  onError: function(errorcode, errormsg) {
    var error = Cc['@flock.com/error;1'].createInstance(Ci.flockIError);
    error.serviceErrorCode = errorcode;
    error.serviceErrorString = errormsg;
    // Stupid server doesn't return any correct XML, but just a plain text error message
    if (errorcode.match("blog doesn't exist")) {
      error.serviceErrorString = errorcode;
      error.errorCode = Ci.flockIError.BLOG_INVALID_AUTH;
    }
    else
      error.errorCode = Ci.flockIError.BLOG_UNKNOWN;
    this.listener.onError(error);
  },
  onFault: function(errorcode, errormsg) {
    var error = Cc['@flock.com/error;1'].createInstance(Ci.flockIError);
    error.serviceErrorCode = errorcode;
    error.serviceErrorString = errormsg;
    switch (errorcode) {
      case 403: // Invalid login/pass
        error.errorCode = Ci.flockIError.BLOG_INVALID_AUTH;
        break;
      default: // Unknown error code
        error.errorCode = Ci.flockIError.BLOG_UNKNOWN;
    }
    this.listener.onFault(error);
  }
}


function flockBSService () {
  var obs = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
  obs.addObserver(this, 'xpcom-shutdown', false);
  this.status = Ci.flockIWebService.STATUS_UNKNOWN;
  this.initialized = false;

  this._ctk = {
    interfaces: [
      "nsISupports",
      "nsIClassInfo",
      "nsIObserver",
      "nsISupportsCString",
      "flockIWebService",
      "flockIAuthenticateNewAccount",
      "flockIManageableWebService",
      "flockIBlogWebService"
    ],
    shortName: "blogsome",
    fullName: "Blogsome",
    description: "Blogsome Web Service",
    favicon: BLOGSOME_FAVICON,
    CID: BLOGSOME_CID,
    contractID: BLOGSOME_CONTRACTID,
    accountClass: flockBSAccount
  };
  this._profiler = Cc["@flock.com/profiler;1"].getService(Ci.flockIProfiler);

  this.init();
}

// nsIObserver
flockBSService.prototype.observe = function flockBSService_observe(subject, topic, state) {
  switch (topic) {
    case 'xpcom-shutdown':
      var obs = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
      obs.removeObserver(this, 'xpcom-shutdown');
      return;
  }
}

// flockIWebService implementation
flockBSService.prototype.addAccount =
function flockBSService_addAccount(aUsername, aPassword, aListener)
{
  //DEBUG("{flockIWebService}.addAccount('"+aUsername+"', 'XXXXXXXX', ...)");
  //DEBUG(" THIS FUNCTION IS DEPRECATED AND SHOULD BE REPLACED WITH A CALL TO addAccountById() !");
  return this.addAccountById(aUsername, true, aListener);
}

flockBSService.prototype.addAccountById =
function flockBSService_addAccountById(aUsername, aIsTransient, aListener)
{
  var accountURN = this.urn+":"+aUsername;
  var account = new this.faves_coop.Account(accountURN, {
    name: aUsername,
    serviceId: BLOGSOME_CONTRACTID,
    service: this.bsService,
    accountId: aUsername,
    isPollable : false,
    isTransient: aIsTransient,
    favicon: this.icon,
    URL: this.url,
    showInSidebar: false
  });
  this.faves_coop.accounts_root.children.addOnce(account);
  // this.USER = blAccount.id();
  // var acct = this.getAccount(blAccount.id());
  this.USER = accountURN;

  // Add the blog account
  var wpsvc = this;
  var listener = {
    onResult: function(aResult) {
      var theBlog;
      while (aResult.hasMoreElements()) {
        theBlog = aResult.getNext();
        theBlog.QueryInterface(Ci.flockIBlogAccount);
        theCoopBlog = new wpsvc.faves_coop.Blog(accountURN+":"+theBlog.blogid, {
          name: theBlog.title,
          title: theBlog.title,
          blogid: theBlog.blogid,
          URL: theBlog.URL,
          apiLink: theBlog.URL+'xmlrpc.php'
        });
        account.children.addOnce(theCoopBlog);

        // Comments: create the "My Blogs" folder if needed
        var feedManager = Components.classes["@flock.com/feed-manager;1"].getService(Components.interfaces.flockIFeedManager);
        var blogFolder = null;
        var _enum = feedManager.getFeedContext("news").getRoot().getChildren();
        while (_enum.hasMoreElements() && !blogFolder) {
          var candidate = _enum.getNext();
          if (candidate.getTitle() == "My Blogs")
            blogFolder = candidate;
        }
        if (!blogFolder)
          blogFolder = feedManager.getFeedContext("news").getRoot().addFolder("My Blogs");
        // Comments: add the stream
        var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
        var uri = ios.newURI(theBlog.URL+"comments/feed/", null, null);
        var feedManagerListener = {
          onGetFeedComplete: function(feed) {
            blogFolder.subscribeFeed(feed);
            Cc["@flock.com/metrics-service;1"]
            .getService(Ci.flockIMetricsService)
            .report("FeedsSidebar-AddFeed",  "BlogsomeNewAccount");
          },
          onError: function(error) {
          }
        }
        feedManager.getFeed(uri, feedManagerListener);
      }
      if (aListener) aListener.onSuccess(acct, "addAccount");
    },
    onFault: function(aError) {
      debug("flockBlogsomeService: fault in addAccount: "+aError);
      wpsvc.faves_coop.accounts_root.children.remove(account);
      account.destroy();
      if(aListener) {
        aListener.onError(null, 'FAULT', aError);
      }
    },
    onError: function(aError) {
      debug("flockBlogsomeService: error in addAccount: "+aError);
      wpsvc.faves_coop.accounts_root.children.remove(account);
      account.destroy();
      if(aListener) {
        aListener.onError(null, 'ERROR', aError);
      }
    }
  };

  var apiLink = 'http://'+aUsername+'.blogsome.com/xmlrpc.php';
  this.getUsersBlogs(listener, apiLink);

  var acct = this.getAccount(accountURN);
  return acct;
}


flockBSService.prototype.removeAccount =
function(aUrn)
{
  this.acUtils.removeAccount(aUrn);
}


flockBSService.prototype.getAccount =
function(aUrn)
{
  this.logger.info("{flockIWebService}.getAccount('"+aUrn+"')");
  var acctCoop = this.faves_coop.get(aUrn);
  var acct = new flockBSAccount();
  acct.urn = aUrn;
  acct.username = acctCoop.username;
  return acct;
}


flockBSService.prototype.init =
function ()
{
  DEBUG(".init()");

  if (this.initialized) return;
  this.initialized = true;

  var evtID = this._profiler.profileEventStart("blogsome-init");

  this.prefService = Components.classes["@mozilla.org/preferences-service;1"]
                               .getService(Components.interfaces.nsIPrefBranch);
  if ( this.prefService.getPrefType(SERVICE_ENABLED_PREF) &&
       !this.prefService.getBoolPref(SERVICE_ENABLED_PREF) )
  {
    DEBUG("Pref "+SERVICE_ENABLED_PREF+" set to FALSE... not initializing.");
    var catMgr = Cc["@mozilla.org/categorymanager;1"].getService(Ci.nsICategoryManager);
    catMgr.deleteCategoryEntry("wsm-startup", CATEGORY_COMPONENT_NAME, true);
    catMgr.deleteCategoryEntry("flockWebService", CATEGORY_ENTRY_NAME, true);
    return;
  }

  // Logger
  this.logger = Cc['@flock.com/logger;1'].createInstance(Ci.flockILogger);
  this.logger.init("blogsome");

  // Attributes of flockIBlogWebService
  this.supportsCategories = 2;
  this.supportsPostReplace = true;
  this.metadataOverlay = "";

  this.acUtils = Cc["@flock.com/account-utils;1"].getService(Ci.flockIAccountUtils);

  this.faves_coop = Cc["@flock.com/singleton;1"]
                    .getService(Ci.flockISingleton)
                    .getSingleton("chrome://flock/content/common/load-faves-coop.js")
                    .wrappedJSObject;
	this.account_root = this.faves_coop.accounts_root;

	this.bsService = new this.faves_coop.Service('urn:blogsome:service');
  this.bsService.name = 'blogsome';
  this.bsService.desc = 'The Blogsome.com Service';
  this.bsService.logoutOption = false;
  this.bsService.domains = "blogsome.com";
  this.bsService.serviceId = BLOGSOME_CONTRACTID;

  this.urn = this.bsService.id();
  this.url = "http://www.blogsome.com";

  this.webDetective = this.acUtils.useWebDetective("blogsome.xml");

  this._profiler.profileEventEnd(evtID, "");
}


flockBSService.prototype.refresh =
function flockBSService_refresh(aURN, aListener)
{
	debug ("flockBSService refresh with aURN of " + aURN + "\n");

	// Introspection against what we're syncing - Identity or Account or Item?
	var refreshItem = this.faves_coop.get(aURN);

  if (refreshItem instanceof this.faves_coop.Account) {
	}
  else if (refreshItem instanceof this.faves_coop.Favorite) {
	}
  else {
		throw Components.results.NS_ERROR_ABORT;
	}
}

flockBSService.prototype.refreshAccount =
function flockBSService_refreshAccount (aURN, aListener) {
  debug("WPService - refreshAccount with aURN of " + aURN);
}


// BEGIN flockIBlogWebService interface


flockBSService.prototype.newPost =
function(aListener, aBlogId, aPost, aPublish, aNotifications)
{
  var mtService = Cc['@flock.com/blog/service/movabletype;1'].getService(Ci.flockIBlogWebService);
  mtService.newPost(aListener, aBlogId, aPost, aPublish, aNotifications);
}

flockBSService.prototype.editPost =
function(aListener, aBlogId, aPost, aPublish, aNotifications)
{
  var mtService = Cc['@flock.com/blog/service/movabletype;1'].getService(Ci.flockIBlogWebService);
  mtService.editPost(aListener, aBlogId, aPost, aPublish, aNotifications);
}

flockBSService.prototype.deletePost =
function(aListener, aBlogId, aPostid)
{
  var mtService = Cc['@flock.com/blog/service/movabletype;1'].getService(Ci.flockIBlogWebService);
  mtService.deletePost(aListener, aBlogId, aPostid);
}

flockBSService.prototype.getUsersBlogs =
function(aListener, aUrl)
{
  var username = this.faves_coop.get(this.USER).name;
  debug("USER: "+username+"\n");
  var pw = this.acUtils.getPassword(this.urn+':'+username);
  debug(" ^^^^^^^^^ Get the password for "+this.urn+':'+username+"\n");

  var listener = new userBlogsListener(aListener, false);
  var xmlrpcServer = new flockXmlRpcServer (aUrl);
  var args = ["flockbrowser", username, pw.password];
  xmlrpcServer.call("blogger.getUsersBlogs", args, listener);
}

flockBSService.prototype.getRecentPosts =
function(aListener, aBlogId, aNumber)
{
  var mtService = Cc['@flock.com/blog/service/movabletype;1'].getService(Ci.flockIBlogWebService);
  mtService.getRecentPosts(aListener, aBlogId, aNumber);
}

flockBSService.prototype.getCategoryList =
function(aListener, aBlogId)
{
  var mtService = Cc['@flock.com/blog/service/movabletype;1'].getService(Ci.flockIBlogWebService);
  mtService.getCategoryList(aListener, aBlogId);
}

// END flockIBlogWebService interface

// BEGIN flockIManageableWebService interface
flockBSService.prototype.docRepresentsSuccessfulLogin =
function flockBSService_docRepresentsSuccessfulLogin(aDocument)
{
  this.logger.debug("{flockIManageableWebService}.docRepresentsSuccessfulLogin(aDocument)");
  aDocument.QueryInterface(Components.interfaces.nsIDOMHTMLDocument);
  return this.webDetective.detect("blogsome", "loggedin", aDocument, null);
}

flockBSService.prototype.getAccountIDFromDocument =
function flockBSService_getAccountIDFromDocument(aDocument)
{
  this.logger.debug("{flockIManageableWebService}.getAccountIDFromDocument(aDocument)");
  aDocument.QueryInterface(Components.interfaces.nsIDOMHTMLDocument);

  // The URL is the form http://<username>.blogsome.com
  var ios = Components.classes["@mozilla.org/network/io-service;1"]
                      .getService(Components.interfaces.nsIIOService);
  var uri = ios.newURI(aDocument.URL, null, null);
  return uri.host.split(".")[0];
}

flockBSService.prototype.ownsDocument =
function flockBSService_ownsDocument(aDocument)
{
  this.logger.debug("{flockIManageableWebService}.ownsDocument(aDocument)");
  aDocument.QueryInterface(Components.interfaces.nsIDOMHTMLDocument);
  var ios = Components.classes["@mozilla.org/network/io-service;1"]
                      .getService(Components.interfaces.nsIIOService);
  var uri = ios.newURI(aDocument.URL, null, null);
  if ((uri.host == "blogsome.com") || (uri.host.indexOf(".blogsome.com") > 0)) {
    return true;
  }
  else {
    return false;
  }
}

flockBSService.prototype.updateAccountStatusFromDocument =
function flockBSService_updateAccountStatusFromDocument(aDocument)
{
  this.logger.debug("{flockIManageableWebService}.updateAccountStatusFromDocument(aDocument)");
  if (this.ownsDocument(aDocument)) {
    if (this.docRepresentsSuccessfulLogin(aDocument)) {
      var accountID = this.getAccountIDFromDocument(aDocument);
      var acctURN = this.acUtils.getAccountURNById(this.urn, accountID);
      var accounts = this.faves_coop.Account.find({serviceId: BLOGSOME_CONTRACTID});
      for (var i = 0; i < accounts.length; i++) {
        if (accounts[i].id() == acctURN) {
          accounts[i].isAuthenticated = true;
        } else {
          accounts[i].isAuthenticated = false;
        }
      }
    } else {
      var login = aDocument.getElementById("Login");
      if (login) {
        this.acUtils.markAllAccountsAsLoggedOut(BLOGSOME_CONTRACTID);
      }
    }
  }
}

flockBSService.prototype.logout =
function flockBSService_logout()
{
  this.logger.debug("{flockIManageableWebService}.logout()");
  var cookieManager = Cc["@mozilla.org/cookiemanager;1"]
                      .getService(Ci.nsICookieManager);
  var allCookies = cookieManager.enumerator;
  while (allCookies.hasMoreElements()) {
    var cookie = allCookies.getNext()
                           .QueryInterface(Ci.nsICookie);
    if (cookie.host.match("blogsome.com")) {
      cookieManager.remove(cookie.host, cookie.name, cookie.path, false);
    }
  }
}

flockBSService.prototype.logout =
function flockBSService_logout()
{
  this.logger.debug("{flockIManageableWebService}.logout()");
  var cookieManager = Cc["@mozilla.org/cookiemanager;1"]
                      .getService(Ci.nsICookieManager);
  var allCookies = cookieManager.enumerator;
  while (allCookies.hasMoreElements()) {
    var cookie = allCookies.getNext()
                           .QueryInterface(Ci.nsICookie);
    if (cookie.host.match("blogsome.com")) {
      cookieManager.remove(cookie.host, cookie.name, cookie.path, false);
    }
  }
}
// END flockIManageableWebService interface


// ================================================
// ========== BEGIN XPCOM Module support ==========
// ================================================

function createModule(aParams) {
  var Cc = Components.classes;
  var Ci = Components.interfaces;
  var Cr = Components.results;
  return {
    registerSelf: function (aCompMgr, aFileSpec, aLocation, aType) {
      aCompMgr.QueryInterface(Ci.nsIComponentRegistrar);
      aCompMgr.registerFactoryLocation( aParams.CID, aParams.componentName,
                                        aParams.contractID, aFileSpec,
                                        aLocation, aType );
      var catMgr = Cc["@mozilla.org/categorymanager;1"]
        .getService(Ci.nsICategoryManager);
      if (!aParams.categories) { aParams.categories = []; }
      for (var i = 0; i < aParams.categories.length; i++) {
        var cat = aParams.categories[i];
        catMgr.addCategoryEntry( cat.category, cat.entry,
                                 cat.value, true, true );
      }
    },
    getClassObject: function (aCompMgr, aCID, aIID) {
      if (!aCID.equals(aParams.CID)) { throw Cr.NS_ERROR_NO_INTERFACE; }
      if (!aIID.equals(Ci.nsIFactory)) { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }
      return { // Factory
        createInstance: function (aOuter, aIID) {
          if (aOuter != null) { throw Cr.NS_ERROR_NO_AGGREGATION; }
          var comp = new aParams.componentClass();
          if (aParams.implementationFunc) { aParams.implementationFunc(comp); }
          return comp.QueryInterface(aIID);
        }
      };
    },
    canUnload: function (aCompMgr) { return true; }
  };
}

// NS Module entrypoint
function NSGetModule(aCompMgr, aFileSpec) {
  return createModule({
    componentClass: flockBSService,
    CID: BLOGSOME_CID,
    contractID: BLOGSOME_CONTRACTID,
    componentName: CATEGORY_COMPONENT_NAME,
    implementationFunc: function (aComp) { getCompTK().addAllInterfaces(aComp); },
    categories: [ // "flock-startup" is automagically added
      { category: "wsm-startup", entry: CATEGORY_COMPONENT_NAME, value: BLOGSOME_CONTRACTID },
      { category: "flockWebService", entry: CATEGORY_ENTRY_NAME, value: BLOGSOME_CONTRACTID }
    ]
  });
}

// ========== END XPCOM Module support ==========




/* ********** Account Class ********** */

function flockBSAccount() {
  this.logger = Cc['@flock.com/logger;1'].createInstance(Ci.flockILogger);
  this.logger.init("blogsomeAccount");

  this.faves_coop = Cc["@flock.com/singleton;1"]
                    .getService(Ci.flockISingleton)
                    .getSingleton("chrome://flock/content/common/load-faves-coop.js")
                    .wrappedJSObject;

  this.acUtils = Cc["@flock.com/account-utils;1"].getService(Ci.flockIAccountUtils);

  this.service = Cc[BLOGSOME_CONTRACTID].getService(Ci.flockIBlogWebService)
}

// nsISupports implementation
flockBSAccount.prototype.QueryInterface = function(iid) {
  if (!iid.equals(Ci.nsISupports) &&
    !iid.equals(Ci.flockIWebServiceAccount) &&
    !iid.equals(Ci.flockIBlogWebServiceAccount))
  {
    throw Components.results.NS_ERROR_NO_INTERFACE;
  }
  return this;
}

// flockIWebServiceAccount implementation
flockBSAccount.prototype.login = function(listener) {
  this.logger.info("{flockIWebServiceAccount}.login()");
  if (listener) {
    listener.onSuccess(this, "login");
  }
}
flockBSAccount.prototype.logout = function(listener) {
  this.logger.info("{flockIWebServiceAccount}.logout()");
  var c_acct = this.faves_coop.get(this.urn);
  if (c_acct.isAuthenticated) {
    c_acct.isAuthenticated = false;
    var cookieManager = Components.classes["@mozilla.org/cookiemanager;1"]
                                  .getService(Components.interfaces.nsICookieManager);
    var allCookies = cookieManager.enumerator;
    var cookieHost = c_acct.accountId+".blogsome.com";
    while (allCookies.hasMoreElements()) {
      var cookie = allCookies.getNext()
                             .QueryInterface(Components.interfaces.nsICookie);
      if (cookie.host == cookieHost) {
        cookieManager.remove(cookieHost, cookie.name, cookie.path, false);
      }
    }
  }
  if (listener) {
    listener.onSuccess(this, "logout");
  }
}
flockBSAccount.prototype.activate = function(aListener) {
  this.logger.info("{flockIWebServiceAccount}.activate()");
}
flockBSAccount.prototype.deactivate = function() {
  this.logger.info("{flockIWebServiceAccount}.deactivate()");
}
flockBSAccount.prototype.keep = function() {
  var c_acct = this.faves_coop.get(this.urn);
  c_acct.isTransient = false;
  this.acUtils.makeTempPasswordPermanent(this.service.urn+':'+c_acct.accountId);
}
flockBSAccount.prototype.remove = function() {
  this.service.removeAccount(this.urn);
}

// flockIBlogWebServiceAccount implementation
flockBSAccount.prototype.getBlogs = function() {
  this.logger.info("{flockIBlogWebServiceAccount}.getBlogs()");
  var blogsEnum = {
    QueryInterface : function(iid) {
      if (!iid.equals(Ci.nsISupports) &&
          !iid.equals(Ci.nsISimpleEnumerator))
      {
        throw Components.results.NS_ERROR_NO_INTERFACE;
      }
      return this;
    },
    hasMoreElements : function() {
      return false;
    },
    getNext : function() {
    }
  };
  return blogsEnum;
}
