// 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("flockTypepadService: "+x+"\n"); }

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

const TYPEPAD_CID = Components.ID('{b83be4a8-c826-4e24-b8dd-83c2af2d6735}');
const TYPEPAD_NAME = 'Flock Typepad Service';
const TYPEPAD_CONTRACTID = '@flock.com/blog/typepad;1';

const TYPEPAD_FAVICON = "chrome://flock/content/services/typepad/favicon.png";
const SERVICE_ENABLED_PREF          = "flock.service.typepad.enabled";
const CATEGORY_COMPONENT_NAME       = "Typepad JS Component"
const CATEGORY_ENTRY_NAME           = "typepad"

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");

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

function clearTypepadCookies() {
  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("typepad.com")) {
      cookieManager.remove(cookie.host, cookie.name, cookie.path, false);
    }
  }
}

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

userBlogsListener.prototype =
{
  // aResult is an Array 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;
    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;
        error.errorString = "Bad authentication";
        break;
      default: // Unknown error code
        error.errorCode = Ci.flockIError.BLOG_UNKNOWN;
        error.errorString = "Unknown Error";
    }
    this.listener.onFault(error);
  }
}


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

  this._ctk = {
    interfaces: [
      "nsISupports",
      "nsISupportsCString",
      "nsIClassInfo",
      "nsIObserver",
      "nsITimerCallback",
      "flockIWebService",
      "flockIManageableWebService",
      "flockIBlogWebService",
    ],
    shortName: "typepad",
    fullName: "Typepad",
    description: TYPEPAD_NAME,
    favicon: TYPEPAD_FAVICON,
    CID: TYPEPAD_CID,
    contractID: TYPEPAD_CONTRACTID,
    accountClass: flockTPAccount
  };
  this._profiler = Cc["@flock.com/profiler;1"].getService(Ci.flockIProfiler);

  this.init();
}

// nsIObserver
flockTPService.prototype.observe = function flockTPService_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
flockTPService.prototype.addAccount =
function flockTPService_addAccount(aUsername, aIsTransient, aListener)
{
  var accountURN = this.acUtils.createAccount(this,
                                              aUsername,
                                              aUsername,
                                              null,
                                              aIsTransient);
  var account = this.faves_coop.get(accountURN);
  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.title, {
          name: theBlog.title,
          title: theBlog.title,
          blogid: theBlog.blogid,
          URL: theBlog.URL,
          apiLink: 'http://www.typepad.com/t/api'
        });
        account.children.addOnce(theCoopBlog);
      }
      if (aListener) aListener.onSuccess(acct, "addAccount");
    },
    onFault: function(aError) {
      wpsvc.faves_coop.accounts_root.children.remove(account);
      account.destroy();
      if(aListener) {
        aListener.onError(null, 'FAULT', aError);
      }
    },
    onError: function(aError) {
      wpsvc.faves_coop.accounts_root.children.remove(account);
      account.destroy();
      if(aListener) {
        aListener.onError(null, 'ERROR', aError);
      }
    }
  };

  var apiLink = 'http://www.typepad.com/t/api';
  this.getUsersBlogs(listener, apiLink);

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

flockTPService.prototype.logout =
function flockTPService_logout() {
  this.logger.debug("{flockIWebService}.logout()");
  clearTypepadCookies();
}


var gStrings = {
  "domains": "typepad.com",
  "userlogin": "http://www.typepad.com/t/app"
}

flockTPService.prototype.init = function () {

  DEBUG(".init()");

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

  var evtID = this._profiler.profileEventStart("typepad-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("typepad");

  // 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.tpService = new this.faves_coop.Service('urn:typepad:service');
  this.tpService.name = 'typepad';
  this.tpService.desc = 'The Typepad.com Service';
  this.tpService.logoutOption = false;
  this.tpService.serviceId = TYPEPAD_CONTRACTID;
  
  this.webDetective = this.acUtils.useWebDetective("typepad.xml");
  for (var s in gStrings) {
    gStrings[s] = this.webDetective.getString("typepad", s, gStrings[s]);
  }
  this.tpService.domains = gStrings["domains"];
  this.tpService.loginURL = gStrings["userlogin"];

  this.urn = this.tpService.id();
  this.url = "http://www.typepad.com";

  // Initialize member that specifies path for localized string bundle
  this._stringBundlePath = "";

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


flockTPService.prototype.refresh =
function flockTPService_refresh(aURN, aListener) {
	debug ("flockTPService 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;
	}
}

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


// BEGIN flockIBlogWebService interface

flockTPService.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);
}

flockTPService.prototype.editPost =
function(aListener, aBlogId, aPost, aPublish, aNotifications){
  // [bug 8596] Setting categories in editPost doesn't work well on Typepad,
  // so we need to do it manually
  var mtService = Cc['@flock.com/blog/service/movabletype;1'].getService(Ci.flockIBlogWebService);

  var categories = [];
  while (aPost.categories.hasMoreElements()) {
    var category = aPost.categories.getNext();
    category.QueryInterface(Ci.flockIBlogCategory);
    categories.push(category);
  }

  var listener = {
    onResult: function(aResult) {
      var gBlogService = Cc['@flock.com/flock-blog;1'].getService(Ci.flockIBlogService);
      var account = gBlogService.getAccount(aBlogId);
      mtService.setPostCategories(aListener, account, parseInt(aPost.postid), new simpleEnumerator(categories));
    },
    onError: function(error) {
      aListener.onError(error);
    }, 
    onFault: function(error) {
      aListener.onFault(error);
    } 
  };

  mtService.editPost(listener, aBlogId, aPost, aPublish, aNotifications);
}

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

flockTPService.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);

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

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

flockTPService.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
flockTPService.prototype.getAccountIDFromDocument =
function flockTPService_getAccountIDFromDocument(aDocument)
{
  this.logger.debug("{flockIManageableWebService}.getAccountIDFromDocument(aDocument)");

  var results = Cc["@mozilla.org/hash-property-bag;1"]
                .createInstance(Ci.nsIWritablePropertyBag2);
  
  if (this.webDetective.detect("typepad", "accountinfo", aDocument, results)) {
    return results.getPropertyAsAString("accountid");
  } else if (this.lastPassword) {
    return this.lastPassword.user;
  } else {
    return null;
  }
}

flockTPService.prototype.getCredentialsFromForm =
function flockTPService_getCredentialsFromForm(aForm)
{
  this.logger.debug("{flockIManageableWebService}.getCredentialsFromForm(aForm)");
  aForm.QueryInterface(Components.interfaces.nsIDOMHTMLFormElement);
  // Keep it for getAccountIDFromDocument
  this.lastPassword = this.acUtils.extractPasswordFromHTMLForm(aForm);
  return {
    QueryInterface: function(aIID) {
      if (!aIID.equals(Components.interfaces.nsISupports) &&
          !aIID.equals(Components.interfaces.nsIPassword) &&
          !aIID.equals(Components.interfaces.flockIPassword)) { 
        throw Components.interfaces.NS_ERROR_NO_INTERFACE;
      }
      return this;
    },
    host: "",
    user: this.lastPassword.user,
    password: this.lastPassword.password,
    formType: "login"
  };
//  return this.lastPassword;
}

flockTPService.prototype.ownsLoginForm =
function flockTPService_ownsLoginForm(aForm)
{
  this.logger.debug("{flockIManageableWebService}.ownsLoginForm(aForm)");
  aForm.QueryInterface(Components.interfaces.nsIDOMHTMLFormElement);
  return this.webDetective.detectForm("typepad", "ownsLoginForm", aForm, null);
}

flockTPService.prototype.updateAccountStatusFromDocument =
function flockTPService_updateAccountStatusFromDocument(aDocument, aAcctURN)
{
  this.logger.debug("updateAccountStatusFromDocument('" + aAcctURN + "')");
  if (aAcctURN) {
    this.acUtils.ensureOnlyAuthenticatedAccount(aAcctURN);
  } else if (this.webDetective
                 .detect("typepad", "loggedout", aDocument, null))
  {
    this.acUtils.markAllAccountsAsLoggedOut(TYPEPAD_CONTRACTID);
  }
}
// END flockIManageableWebService interface



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

function createModule(aParams) {
  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: flockTPService,
    CID: TYPEPAD_CID,
    contractID: TYPEPAD_CONTRACTID,
    componentName: CATEGORY_COMPONENT_NAME,
    implementationFunc: function (aComp) { getCompTK().addAllInterfaces(aComp); },
    categories: [
      { category: "wsm-startup", entry: CATEGORY_COMPONENT_NAME, value: TYPEPAD_CONTRACTID },
      { category: "flockWebService", entry: CATEGORY_ENTRY_NAME, value: TYPEPAD_CONTRACTID }
    ]
  });
}

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


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

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

  this._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);
}

// nsISupports implementation
flockTPAccount.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
flockTPAccount.prototype.login = function(listener) {
  this.logger.info("{flockIWebServiceAccount}.login()");
  if (listener) {
    listener.onSuccess(this, "login");
  }
}

flockTPAccount.prototype.logout = function(listener) {
  this.logger.info("{flockIWebServiceAccount}.logout()");
  clearTypepadCookies();
  if (listener) {
    listener.onSuccess(this, "logout");
  }
}

flockTPAccount.prototype.activate = function(aListener) {
  this.logger.info("{flockIWebServiceAccount}.activate()");
}

flockTPAccount.prototype.deactivate = function(aListener) {
  this.logger.info("{flockIWebServiceAccount}.deactivate()");
}

flockTPAccount.prototype.keep = function(aListener) {
  var coopAccount = this._coop.get(this.urn);
  coopAccount.isTransient = false;
  var key = coopAccount.service.id() + ":" + coopAccount.accountId;
  this.acUtils.makeTempPasswordPermanent(key);

  if (aListener && aListener.onSuccess) {
    aListener.onSuccess(this, "keep");
  }
}

// flockIBlogWebServiceAccount implementation
flockTPAccount.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;
}
