 Emojis.template = (emoji) ->
   "<img src='#{Emojis.basePath()}/#{imagePath(emoji)}' title='#{emoji.alias}' alt='#{emoji.emoji or emoji.alias}' class='emoji'>"
 
+# Replace emoji shortnames with their unicode version.
+Emojis.toUnicode = (text) ->
+  parse text, (emoji) ->
+    emoji.emoji
+
+# Replace emoji shortnames with images.
 Emojis.parse = (text) ->
-  if typeof text isnt 'string'
-    return ''
-
-  text = text.toString()
-
-  text
-  .replace smileyRegexp, (match, smiley, nose) ->
-    smiley = smiley.toUpperCase()
-    smiley = if nose then smiley.replace(/:-/g, ':') else smiley
-
-    if emoji = Emojis.findOne(ascii: smiley)
-      return Emojis.template(emoji)
-    else
-      return match
-
-  .replace shortnameRegexp, (match, alias) ->
-    if emoji = Emojis.findOne(alias: alias)
-      return Emojis.template(emoji)
-    else
-      return match
+  parse(text, Emojis.template)


Emojis = new Mongo.Collection 'emojis',
  transform: (emoji) ->
    
    # Shortcut helpers

    emoji.path = Emojis.basePath() + '/' + imagePath(emoji)
    
    emoji.toHTML = ->
      Emojis.template(this)


  Emojis._ensureIndex(alias: 1)
  Emojis._ensureIndex(ascii: 1)


# General parse function.
#
# Parses `text` and returns emoji objects from :shortnames: and ASCII
# smileys (:D).
#
# Optionally takes a function which can transform the return value.
parse = (text, fn) ->
  check text, String
  check fn, Match.Optional(Function)

  text
  .replace smileyRegexp, (match, smiley, nose) ->
    smiley = smiley.toUpperCase()
    smiley = if nose then smiley.replace(/:-/g, ':') else smiley

    emoji = Emojis.findOne(ascii: smiley)

    if emoji
      return if fn then fn(emoji) else emoji
    else
      return match

  .replace shortnameRegexp, (match, alias) ->
    emoji = Emojis.findOne(alias: alias)

    if emoji
      return if fn then fn(emoji) else emoji
    else
      return match

Emojis._basePath = '/images/emojis'

