/**
 * Binary tools - Ubiquity commands for converting from and to binary
 *
 * Updated for Parser 2 by KWierso
 * Copyright (c) 2009 Kilian Valkhof (kilianvalkhof.com)
 * Licensed under the MIT license. http://www.opensource.org/licenses/mit-license.php
 */

CmdUtils.CreateCommand({
  names: ["binary-to"],
  arguments: [ {role: 'object',
                nountype: noun_arb_text,
                label: "some text"} ],
  homepage: "http://kilianvalkhof.com/",
  author: {name: "Kilian Valkhof"},
  license: "MIT",
  description: "Convert text to binary.",
  help: "Select a text string or type in a text string and it will be converted to binary",

  _string2bin : function(s) {
    var b = [];
    var last = s.length;
    for (var i = 0; i < last; i++) {
      var d = s.charCodeAt(i);
      if (d < 128) {
        b[i] = this._dec2Bin(d);
      } else {
        var c = s.charAt(i);
        displayMessage(c + ' is NOT an ASCII character');
        b[i] = -1;
        }
      }
    return b.join(' ');
  },
  _dec2Bin : function(d) {
    var b = '';
    for (var i = 0; i < 8; i++) {
      b = (d%2) + b;
      d = Math.floor(d/2);
    }
    return b;
  },
  preview: function( pblock, input) {
    var template = "The selection: <br><i>${selection}</i><br> will be converted to: <br><i>${binary}</i>";
    pblock.innerHTML = CmdUtils.renderTemplate(template, {"selection":input.object.text, "binary": this._string2bin(input.object.text)});
  },
  execute: function(input) {
    CmdUtils.setSelection( this._string2bin(input.object.text) );
  }
});

CmdUtils.CreateCommand({
  names: ["binary-from"],
  arguments: [ {role: 'object',
                nountype: noun_arb_text,
                label: 'some binary'} ],
  homepage: "http://kilianvalkhof.com/",
  author: {name: "Kilian Valkhof"},
  license: "MIT",
  description: "Convert binary to readable text.",
  help: "Select a binary string or type in a binary string and it will be converted to readable text",

  _bin2string : function(b) {
    var b = b.replace(/[^01]/g, "");
    var s= "";
    var length = b.length-(b.length%8);
    for (z=0; z<length; z=z+8) {
        s += String.fromCharCode(parseInt(b.substr(z,8),2));
    }
    return s;
  },
  preview: function( pblock, args) {
    var template = "The selection: <br><i>${selection} &hellip;</i><br> will be converted to: <br><i>${binary}</i>";
    var smalltext = args.object.text.split(" ",13).join(" ");
    pblock.innerHTML = CmdUtils.renderTemplate(template, {"selection":smalltext, "binary": this._bin2string(args.object.text)});
  },
  execute: function(args) {
    CmdUtils.setSelection( this._bin2string(args.object.text) );
  }
});

