{SelfClosingTags} = require "./tags.json"

module.exports =
  class TagBuilder
    constructor: ->
      @builder = []

    beginTag: (name)->
      @builder.push("<#{name}")

    endTag: (name) ->
      if name in SelfClosingTags
        @builder.push("/>")
      else
        @builder.push("</#{name}>")

    addContent: (content) ->
      content ?= ""
      @builder.push(">#{content}")

    addAttrs: (attrs) ->
      for name, value of attrs
        @builder.push("#{name}=\"#{value}\"")

    build: (tagName, args...) ->
      @builder = []

      options = @parseArgs(args)

      @beginTag(tagName)

      options.attributes ?= {}
      @addAttrs(options.attributes)

      if tagName in SelfClosingTags
        if options.content? or options.text?
          throw new Error("Self closing tag \"#{tagName}\" can not have content or text")
      else
        if options.content? and options.text?
          throw new Error("Tag #{tagName} cannot have both text and content")

        content = ""
        content = options.content() if options.content?
        content = options.text if options.text?

        @addContent(content)

      @endTag(tagName)

      @builder.join " "

    parseArgs: (args) ->
      options = {}
      for arg in args
        switch typeof(arg)
          when "function"
            options.content = arg
          when "number", "string"
            options.text = arg.toString()
          else
            options.attributes = arg

      options
