'use strict'

angular.module('<%= appname %>').filter '<%= _.camelize(name) %>', () ->

  (input, arg_reverse) ->

    # local function to reverse a string
    # note: str.split('').reverse().join ''
    #   breaks surrogate pairs - use a custom string splitter
    #   to preserve these, see: http://unicode.org/versions/Unicode3.0.0/ch03.pdf
    #   Page 47: Table 3-1. UTF-8 Bit Distribution
    rev_surrogate = (s) ->
      i = 0
      r = while i < s.length
        c = s.charAt i
        i += 1
        # check for leading sequence ofsurrogate pair
        # and preserver the order
        if i < s.length - 1 and (c.charCodeAt(0) & 0xfc00) is 0xd800
          i += 1
          c + s.charAt i - 1
        # also handle combining characters
        else if i < s.length
          c2 = s.charCodeAt i
          com = while i < s.length and (0x0300 <= c2 <= 0x036f or 0x1DC0 <= c2 <= 0x1DFF or 0x20D0 <= c2 <= 0x20FF or 0xFE20 <= c2 <= 0xFE2F)
            i += 1
            c2 = if i < s.length then s.charCodeAt i else -1
            s.charAt i - 1
          c + com.join ''
        else
          c
      # can now do the normal reverse and join as pairs will remain in correct order
      # since they are lef as two character strings in the 'r' array
      r.reverse().join ''

    # here is the actual sample filter code
    # in view: "... | thisFilter"            just capitalises
    #    also: "... | thisFilter:false"      just capitalises
    #     and: "... | thisFilter:true"       reverses then capitalises
    if arg_reverse
      input = rev_surrogate input
    input.charAt(0).toUpperCase() + input[1..]
