// 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;

var gBlogService = Cc['@flock.com/flock-blog;1'].getService(Ci.flockIBlogService);
var acUtils = Cc["@flock.com/account-utils;1"].getService(Ci.flockIAccountUtils);
var faves_coop = Cc["@flock.com/singleton;1"]
                 .getService(Ci.flockISingleton)
                 .getSingleton("chrome://flock/content/common/load-faves-coop.js")
                 .wrappedJSObject;

var gB = null;
var gNewBlogAccount = null;
var gManualMode = false;
var gParams;

function $(aId) {
  return document.getElementById(aId);
}

function flock_blogWizardLoad() {
  gNewBlogAccount = {};
  gParams = window.arguments[0];
  if (gParams && gParams.defaultToCustom) {
    $('hosted-or-custom').selectedItem = $('radio-custom');
    $('radio-hosted').hidden = true;
    // $('radio-custom').hidden = true;
    $('service-grid').collapsed = true;
    $('custom-blog').collapsed = false;
    refreshNext();
  }

  // Populate the accounts drop-down
  var list = $("blog-api-popup");

  var webServices = gBlogService.services;
  while(webServices.hasMoreElements()) {
    var svc = webServices.getNext();
    svc.QueryInterface(Ci.flockICustomBlogWebService);
    var menuitem = document.createElement("menuitem");
    menuitem.setAttribute('label', svc.name);
    menuitem.setAttribute('value', svc.shortName);
    list.appendChild(menuitem);
  }

  // Populates the service list
  populateServicesPopup($('serviceMenuPopup'));

  refreshNext();

  window.sizeToContent();
}


function refreshNext() {
  $("blogAccountWizard").canAdvance = ($('radio-custom').selected ||
  (($("servicesMenuList" ).selectedItem != null) &&
   ($('service-username').value.length > 0) &&
   ($('service-password').value.length > 0)));
}


function fillFinalUI() {
  if(gB) {
    $("blog-api-menu").value = gB.api;

    $("blog-username").value = gNewBlogAccount.username;
    $("blog-password").value = gNewBlogAccount.password;
    $("blog-uri").value =  gB.apiLink;
  }
}

function blogWizardStartShow() {
  gManualMode = false;
  $("blogAccountWizard").canAdvance = true;
  $('blog-wizard-url').select();
}

function blogWizardStartAdvance() {
  if ($('radio-hosted').selected) {
    $("blogAccountWizard").canAdvance = false;
    $("blogAccountWizard").canRewind = false;
    loginToService();
  }
  else {
    gNewBlogAccount.blogURL = $("blog-wizard-url").value;
    gB = null;
    try {
      $('detect-deck').setAttribute('selectedIndex', '0');
      gBlogService.getCandidatesAPI(new detectFlockListener(), gNewBlogAccount.blogURL);
      $("blogAccountWizard").canAdvance = false;
      $("blogAccountWizard").canRewind = false;
    }
    catch(e) {
      dump("Error "+e+" "+e.fileName+" line "+e.lineNumber+"\n");
      var strbundle = document.getElementById("blogStringBundle");
      var msg = strbundle.getString("flock.blog.wizard.invalidurl");
      alert(msg);
      throw new Error("Musn't advance");
    }
  }
}

function blogAccountWizardSelectAPI(aAPIName) {
  if(aAPIName=="unknown") {
    $("blogAccountWizard").canAdvance = false;
  }
  else {
    $("blogAccountWizard").canAdvance = true;
  }
}

// Helper function to get the formatted string with the brand name
function _getFormattedStringWithBrand(aBundle, aKey) {
  var bundle = Cc["@mozilla.org/intl/stringbundle;1"]
               .getService(Ci.nsIStringBundleService)
               .createBundle("chrome://branding/locale/brand.properties");
  var brand = bundle.GetStringFromName("brandShortName");
  return aBundle.getFormattedString(aKey, [brand]);
}

function blogWizardDetectAdvance() {
  var strbundle = document.getElementById("blogStringBundle");
  if (gB) {
    var label = strbundle.getString("flock.blog.wizard.apidetected.label");
    var msg = _getFormattedStringWithBrand(strbundle,
                                           "flock.blog.wizard.apidetected.msg");
    $("blogWizardConfirmSettings").setAttribute("label", label);
    $("blogWizardConfirmSettings").setAttribute("description", msg);
  }
  else {
    var label = strbundle.getString("flock.blog.wizard.config.label");
    var msg = strbundle.getString("flock.blog.wizard.config.msg");
    $("blogWizardConfirmSettings").setAttribute("label", label);
    $("blogWizardConfirmSettings").setAttribute("description", msg);
  }

  fillFinalUI();
}

function blogWizardDetectRewind() {
  //$("blogAccountWizard").rewind();
//  window.location.reload();
//  $("blogAccountWizard").canAdvance = true;
  window.stop();
  $("blogAccountWizard").goTo("blogWizardStart");
//  $("blogAccountWizard").goTo("blogWizardStart");
//  $("blog-wizard-url").select();
}


function doRestart() {
  $("blogAccountWizard").goTo("blogWizardStart");
  return;
}

function blogWizardConfirmSettingsRewind() {
  dump("Manual mode? "+gManualMode+"\n");
  if (!gManualMode)
    window.setTimeout("doRestart();", 0);
}

function blogWizardConfirmSettingsAdvance() {
  var name = $("blog-api-menu").value;
  gB = {
    api: name,
    apiLink: $("blog-uri").value
  };
}

function blogTitleAdvance() {
}

function blogWizardPasswordShow() {
}

function blogWizardPasswordAdvance() {
  gNewBlogAccount.username = $("blog-wizard-user").value;
  gNewBlogAccount.password = $("blog-wizard-password").value;
  $("blog-username").value = gNewBlogAccount.username;
  $("blog-password").value = gNewBlogAccount.password;

  if(gB) {
    gB.username = gNewBlogAccount.username;
    gB.password = gNewBlogAccount.password;
    var api = gBlogService.getAPIFromShortname(gB.api);
    api.getUsersBlogs(new blogWizardUsersBlogsListener(),
                      gB.apiLink,
                      gNewBlogAccount.username,
                      gNewBlogAccount.password);
    $("blogAccountWizard").canAdvance = false;
  }
}

function blogWizardPasswordRewind() {
  dump("Manual mode? "+gManualMode+"\n");
  if (!gManualMode)
    window.setTimeout("doRestart();", 0);
}

function blogWizardTestAdvance() { }

function blogWizardTestRewind() { }

function blogOptionsAdvance() { }

function blogWizardSaveAccount(aTitle, aAPIName, aAPILink, aBlogID, aUrl) {
  var title = aTitle;
  var count = 1;
  while (flock_blog.service.accountExists(title)) {
    title = aTitle + " (" + count + ")";
    ++count;
    if (flock_blog.service.accountExists(title)) {
      continue;
    }

    var promptService = Cc["@mozilla.org/embedcomp/prompt-service;1"]
      .getService(Ci.nsIPromptService);
    var strbundle = document.getElementById("blogStringBundle");
    var out = {};
    out.value = title;
    var winTitle = strbundle.getString("flock.blog.wizard.inuse.title");
    var winText = strbundle.getString("flock.blog.wizard.inuse.text");
    var result = promptService.prompt(window, winTitle, winText, out, null, {});
    if(result) {
      title = out.value;
    }
    else {
      return false;
    }
  }

  var username = $("blog-username").value;
  var password = $("blog-password").value;

  var url = (aUrl=="")?$("blog-wizard-url").value:aUrl;
  var custom = new faves_coop.Account({
    name: title,
    accountId: username,
    serviceId: '@flock.com/blog/service/'+aAPIName+';1',
    URL: url,
    isTransient: false,
    favicon: "chrome://flock/skin/blog/favicon.png"
  });
  var root = faves_coop.get("http://flock.com/rdf#AccountsRoot");
  root.children.add(custom);

  // ...create a new blog as a child...
  theCoopBlog = new faves_coop.Blog({
    name: title,
    title: title,
    blogid: aBlogID,
    URL: url,
    apiLink: aAPILink
  });
  custom.children.addOnce(theCoopBlog);
  // ... and save the password in the password manager.
  acUtils.setPassword(custom.id(), username, password);
  return true;
}

function blogWizardFinalShow() {
  $("blogAccountWizard").canRewind = false;
  $("blogAccountWizard").getButton("cancel").setAttribute("hidden", true);
}

function blogWizardFinalAdvance() {
  /*
   * Here, go ahead and set the default account to be the last added account
   */
  //var blogSettings = flock_blogGetSettings();
  //var count = blogSettings.getAccountCount();
  //flock_blogSetDefaultAccountIndex(count-1);
  return true;
  //window.close();
}

function detectFlockListener() {
}

detectFlockListener.prototype = {
  onSuccess: function detectFlockListener_onSuccess(aSubject, aTopic) {
    if (aSubject instanceof Ci.nsIPropertyBag) {
      gB = {
        api: aSubject.getProperty("api"),
        apiLink: aSubject.getProperty("apiLink"),
        blogid: aSubject.getProperty("blogid")
      };
    } else {
      gB = null;
      gManualMode = true;
      $("detect-deck").setAttribute("selectedIndex", "1");
      $("blogAccountWizard").canAdvance = true;
      return;
    }

    gManualMode = false;
    fillFinalUI();
    $("blogAccountWizard").canAdvance = true;
    $("blogAccountWizard").advance();
    $("blogAccountWizard").advance();
  },

  onError: function detectFlockListener_onError(aFlockError, aTopic) {
    gManualMode = true;
    switch (aFlockError) {
      case ("NO_API_FOUND"): // FIXME. this is not a FlockError value
      $('detect-deck').setAttribute('selectedIndex', '1');
      $("blogAccountWizard").canAdvance = true;
      break;
      default:
      $('detect-deck').setAttribute('selectedIndex', '2');
    }
  }
};

function blogWizardUsersBlogsListener() {
}

blogWizardUsersBlogsListener.prototype = {
  onResult: function ubl_onResult(aSimpleEnum) {
    aSimpleEnum.QueryInterface(Components.interfaces.nsISimpleEnumerator);
    if (!aSimpleEnum.hasMoreElements()) {
      this.onError();
      return;
    }
    var theBlog;
    while (aSimpleEnum.hasMoreElements()) {
      theBlog = aSimpleEnum.getNext();
      theBlog.QueryInterface(Ci.nsIPropertyBag2);
      var apiName = $("blog-api-menu").value;
      var APILink = (theBlog.getPropertyAsAString("APILink") != "")
                  ? theBlog.getPropertyAsAString("APILink")
                  : document.getElementById("blog-uri").value;
      var title = theBlog.getPropertyAsAString("title");
      var blogID = theBlog.getPropertyAsAString("blogid");
      var url = theBlog.getPropertyAsAString("URL");
      var save = blogWizardSaveAccount(title, apiName, APILink, blogID, url);
      if (!save) {
        $("blogAccountWizard").cancel();
        return;
      }
    }

    $("blogAccountWizard").canAdvance = true;
    $("blogAccountWizard").advance();
  },

  onError: function ubl_onError(aFlockError) {
    //Error; usually happens when there is a problem in the url
    switch (aFlockError.errorCode) {
      case aFlockError.BLOG_INVALID_AUTH:
        $("loginError").setAttribute("hidden", "false");
        $("blogAccountWizard").canAdvance = true;
        $("blogAccountWizard").rewind();
        break;
      case aFlockError.BLOG_UNAVAILABLE:
        $("urlError").setAttribute("hidden", "false");
        $("blogAccountWizard").rewind();
        $("blogAccountWizard").canAdvance = true;
        $("blogAccountWizard").goTo('blogWizardConfirmSettings');
        break;
      case aFlockError.BLOG_NOT_ALLOWED:
        var failTitle = $("blogWizardFinal").getAttribute("failtitle");
        $("blogWizardFinal").setAttribute("label", failTitle);
        $("final-deck").setAttribute("selectedIndex", 1);
        $("blogAccountWizard").canAdvance = true;
        $("blogAccountWizard").advance();
        break;
      default:
        var strbundle = document.getElementById("blogStringBundle");
        var msg = strbundle.getString("flock.blog.wizard.detecterr2");
        var prompts = Cc["@mozilla.org/embedcomp/prompt-service;1"]
                .getService(Ci.nsIPromptService);
        if (prompts.confirm(window, strbundle.getString("flock.blog.wizard.retrieve.error.title"), msg)){
          $("blogAccountWizard").canAdvance = true;
          $("blogAccountWizard").rewind();
        }
        else {
          gManualMode = true;
          $("blogAccountWizard").canAdvance = true;
          $("blogAccountWizard").goTo('blogWizardConfirmSettings');
        }
    }
  },

  onFault: function ubl_onFault(aFlockError) {
    this.onError(aFlockError);
  }
}

function refreshAllSidebars() {
  var windowMediator = Cc["@mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIWindowMediator);

  var allWindows = windowMediator.getEnumerator(null);
  while (allWindows.hasMoreElements()) {
    var win_ = allWindows.getNext();
    if (win_.document.getElementById('sidebar')) {
      try {
        if (win_.document.getElementById('sidebar').contentDocument &&
            win_.document.getElementById('sidebar').contentDocument.getElementById('activeAccountsList')) {
          win_.document.getElementById('sidebar').contentDocument.getElementById('activeAccountsList').builder.rebuild();
        }
      }
      catch (e) {
        // Sometimes the getter on contentDocument throws an exception
      }
    }
  } 
}

/* 
 * When the user choose to set up a hosted blog (not a custom blog)
 */
function loginToService(){
  var acUtils = Cc["@flock.com/account-utils;1"].getService(Ci.flockIAccountUtils);

  var svc = $("servicesMenuList" ).selectedItem.svc;
  var username = $('service-username').value;
  var password = $('service-password').value;

  if ((svc.shortName == 'blogger') && (!username.match('@')))
    username = username + '@gmail.com';

  acUtils.setTempPassword(svc.urn+":"+username, username, password, "flock");
  acUtils.makeTempPasswordPermanent(svc.urn+':'+username);

  var listener = {
  onSuccess: function (account, msg) {
    account.QueryInterface(Ci.flockIWebServiceAccount);

    refreshAllSidebars();

    $("blogAccountWizard").canAdvance = true;
    $("blogAccountWizard").goTo('blogWizardFinal');
    return;
  },
  onError: function (aFlockError, aTopic) {
    var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService( Components.interfaces.nsIPromptService ); 
    promptService.alert(window, "Error", aFlockError.errorString);
    doRestart();
  },
  onFault: function (aFlockError, aTopic) {
    var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService( Components.interfaces.nsIPromptService ); 
    promptService.alert(window, "Fault", aFlockError.errorString);
    doRestart();
  }

  }

  svc.addAccount(username, false, listener);
}


function populateServicesPopup(aPopup) {
  var CATMAN = Cc['@mozilla.org/categorymanager;1'].getService(Ci.nsICategoryManager);
  var e = CATMAN.enumerateCategory('flockWebService');
  while (e.hasMoreElements()) {
  try {
    var entry = e.getNext().QueryInterface(Ci.nsISupportsCString);
    if (!entry) { continue; }
    var contractID = CATMAN.getCategoryEntry('flockWebService', entry.data);
    var svc = Cc[contractID].getService(Ci.flockIWebService);
    svc.QueryInterface(Ci.flockIBlogWebService);
    var account = document.createElement("menuitem");
    account.svc = svc;
    account.setAttribute("value", svc.urn);
    account.setAttribute("src", svc.icon);
    account.setAttribute("label", svc.title);
    aPopup.appendChild(account);
  } catch (ex) {
    // This service is not a flockIBlogWebService
  }
  }
}
