

module.exports = class NoUnnecessaryDoubleQuotes

    rule:
        name: 'no_unnecessary_double_quotes'
        level : 'ignore'
        message : 'Unnecessary double quotes are forbidden'
        description: '''
            This rule prohibits double quotes unless string interpolation is 
            used or the string contains single quotes.
            <pre>
            <code># Double quotes are discouraged:
            foo = "bar"

            # Unless string interpolation is used:
            foo = "#{bar}baz"

            # Or they prevent cumbersome escaping:
            foo = "I'm just following the 'rules'"
            </code>
            </pre>
            Double quotes are permitted by default.
            '''

    tokens: [ 'STRING' ]

    lintToken : (token, tokenApi) ->
        tokenValue = token[1]

        stringValue = tokenValue.match(/^\"(.*)\"$/)
        return false unless stringValue # no double quotes, all OK

        hasLegalConstructs = @isInterpolated(tokenApi) or
            @containsSingleQuote(tokenValue)

        return not hasLegalConstructs

    isInterpolated : (tokenApi) ->
        currentIndex = tokenApi.i
        isInterpolated = false
        lineTokens = tokenApi.tokensByLine[tokenApi.lineNumber]

        # Traverse backwards to find signs that the current string token is
        # generated by the coffee rewriter for string interpolation
        for i in [1..currentIndex]
            token = tokenApi.peek(-i)
            tokenName = token[0]

            if tokenName is ')' and token.stringEnd
                break # No interpolation, we can quit
            else if tokenName is '(' and
                    token.origin?[1] is "string interpolation"
                isInterpolated = true
                break

        return isInterpolated

    containsSingleQuote : (tokenValue) ->
        return tokenValue.indexOf("'") isnt -1
