/**
* Yoda speak - Ubiquity commands for converting text into Yoda Speak
*
* Copyright (c) 2009 Kilian Valkhof (kilianvalkhof.com)
* Licensed under the MIT license. http://www.opensource.org/licenses/mit-license.php
*/

CmdUtils.CreateCommand({
  name: "yoda",
  takes: {"some text": noun_arb_text},
  homepage: "http://kilianvalkhof.com/",
  author: {name: "Kilian Valkhof"},
  license: "MIT",
  description: "Convert text to Yoda speak.",
  help: "Select a text string or type in a text string and it will be converted to Yoda speak. (any sentence with these words: is, be, will, show, do, try, are, teach, have.)",
  
  _yodafy: function(str) {
    var s = this._setcase(this._trim(str));
    var ns;
    var dot = "";
    var p = s.match(/!|\?|\./) || "";
    var occur = s.match(/\s(is|be|will|show|do|try|are|teach|have)\s/);
    if (occur) {    
      if (p) {
        s = s.substring(0, s.length-1);
        dot = p;
      }
      s = s.split(occur[0]);
      occur[0] = occur[0].substring(1, occur[0].length-1);
      ns = s[1] + ", ";
      s[1] = "";
      ns += s.join(" "+occur[0]+" ");
      ns = ns.substring(0, ns.length-1)+dot;
      ns = this._setcase(ns, "upper");
    } else {
      ns = this._setcase(s, "upper");
    }
    return ns;
  },
  _trim: function(s) {
    s = s.replace(/^\s+|\s+$/g, "");
    s = s.replace(/^#/, "");
    return s.replace(/^\s+|\s+$/g, "");
  },
  _setcase: function(l, casing) {
    l = l.split('');
    l[0] = (casing == "upper") ? l[0].toUpperCase() : l[0].toLowerCase();
    l = l.join('');
    var fp = l.match(/\si\s/);
    if (fp) {
      l = l.split(fp);l = l[0]+" I "+l[1];
    }
    return l;
  },
  _multiyoda: function(str) {
    s = str.replace(/(!|\?|\.)/g, '$1\n').split('\n');
    if (s[s.length-1] == "") {var bla = s.pop();}
    var se = s.length;
    for (var i=0;i<se;i++) {
      if(s[i] != "\r") {
         s[i] = this._yodafy(s[i]);
      }
    }
    return s.join(" ");
  },
  preview: function( pblock, input) {
    var template = "<b>You say:</b> <br><i>${selection}</i><br> <b>Yoda says:</b> <br><i>${yoda}</i>";
    pblock.innerHTML = CmdUtils.renderTemplate(template, {"selection":input.text, "yoda": this._multiyoda(input.text)});
  },
  execute: function(input) {CmdUtils.setSelection(this._multiyoda(input.text));}
});
