/*
  TODO
    Re-examine FUEL login creds (instapaper-fuel.js)
    Implement Google Reader compatibility (bookmarklet-remote-source.js)
*/

function _sendMessage(verbose, myTitle, myMessage) {
  if (verbose) {
    displayMessage({icon: "http://www.instapaper.com/favicon.png", title: myTitle, text: myMessage});
  }
}

//remove stored login information, verbose as boolean param
function _resetLogin (verbose) {
  try {
    var passwordManager = Cc["@mozilla.org/login-manager;1"].getService(Ci.nsILoginManager);
    var logins = passwordManager.findLogins({}, "chrome://ubiquity/content", "UbiquityInformationinstapaper", null); 
    var myLogin = logins[0];
    passwordManager.removeLogin(myLogin);
    _sendMessage(verbose, "Success!", "instapaper username and password successfully removed.");
  } catch (e) {
    _sendMessage(verbose, "Error!", "Username and password not removed. This probably means that you didn't have one stored in the first place.");
  }
}

//retrieve login credentials or store new ones if necessary
function _setLogin() {
  var logins = CmdUtils.retrieveLogins("instapaper");
  var login = { name: "instapaper", username: "", password: "" };
  
  if( logins.length > 0 ){
    login = logins[0];
    
  } else {
    
    //prompt for login
    var username = {value: ""};
    var password = {value: ""};
    var check = {value: true};
    var prompts = Cc["@mozilla.org/embedcomp/prompt-service;1"]
                      .getService(Ci.nsIPromptService);
    var result = prompts.promptUsernameAndPassword(null,
                      "Login to instapaper.com",
                      "Please enter your instapaper.com username and password (if you have one):",
                      username, password, null, check);
    
    if (result && username.value.length > 0 && username.value !== null) {//check for empty username, but not password since instapaper does not require passwords 
      //save login
      
      login.username = username.value;
      login.password = password.value;
      
      CmdUtils.savePassword(login); //throws exception if password is empty or null, so user with empty password either has to enter his login creds every time or store a bogus password (which still validates with the instapaper API)
    } else { 
      //require login
      
      _sendMessage(true, "Error", "You must enter your instapaper username for this command to work.");
      login = null;
    }
  }
  return login;
}


CmdUtils.CreateCommand({
  names: ["logout of instapaper", "logout from instapaper", "logout instapaper"],
  homepage: "http://www.duncanandmeg.org/projects/ubiquity-instapaper.php",
  author: {
    name: "Duncan Johnson",
    email: "duncan@duncanandmeg.org"
  },
  license: "GPL",
  description: "Removes username \&amp; password stored by the \<b\>add to instapaper\<\/b\> command. Use this command if you've changed your instapaper.com username or password.",
  icon: "http://www.instapaper.com/favicon.png",
  help: "Your stored instapaper login and password (if you have one) will be removed. The next time you issue the add to instapaper command you will be asked for a new login and password.",
  execute: function execute(args) {
    _resetLogin(true);
  }
});



CmdUtils.CreateCommand({
  names: ["read later", "add to instapaper", "add instapaper"],
  homepage: "http://www.duncanandmeg.org/projects/ubiquity-instapaper.php",
  author: {
    name: "Duncan Johnson",
    email: "duncan@duncanandmeg.org"
  },
  license: "GPL",
  description: "Saves current page to read later on Instapaper.",
  icon: "http://www.instapaper.com/favicon.png",
  help: "If you select some text from the page, it will be stored as the summary. This command will store your instapaper login and password.",
  
  preview: function(previewPane) {
    var page = {
      title: CmdUtils.getDocument().title,
      selection: CmdUtils.getSelection().split(" ",36).join(" ")
    };
    page.selection = (page.selection.length > 0) ? page.selection = page.selection + "..." : "<i>You did not select any text. If you would like to save some summary text, select some text and execute the <b>later</b> command again.</i>" ;
    
    var template = "This page will be added to your instapaper so you can read it later.<p>Preview:</p><blockquote><p><b>${title}</b></p><p>${selection}</p></blockquote>";
    previewPane.innerHTML = CmdUtils.renderTemplate( template, {title: page.title, selection: page.selection} );
  },

  execute: function() {
    //obtain credentials
    var login = _setLogin();
    if (!login) return; //discontinue if no login
    
    //grab page info
    var page = {
      url: CmdUtils.getDocument().URL,
      title: CmdUtils.getDocument().title,
      selection: CmdUtils.getSelection()
    };
  
    //set api params
    var updateUrl = "https://www.instapaper.com/api/add";
    var updateParams = {
      username: login.username,
      password: login.password,
      url: page.url,
      title: page.title,
      selection: page.selection
    };
  
    
    //execute request
    jQuery.ajax({
      type: "POST",
      url: updateUrl,
      data: updateParams,
      error: function(responseData) {
        switch(responseData.status) {
          case 400: //Probably missing a required parameter, such as url.
            _sendMessage(true, "Error " + responseData.status, "Bad request.");
            break;    
          case 403: //bad credentials
            _sendMessage(true, "Error " + responseData.status, "Invalid username or password. Please try again.");
            _resetLogin(false);
            break;
          case 500: //server error
            _sendMessage(true, "Error " + responseData.status, "Instapaper had an unexpected problem. Please try again later.");
            break;
          default: //other error
            _sendMessage(true, "Error " + responseData.status, "Unexpected error.");
        }
      },
      success: function() {
        _sendMessage(true, "Success!", "\"" + page.title + "\" has been added to your instapaper.");
      }
    });  
  }
});

