module NumberFormattable
  extend ActiveSupport::Concern

  def precision
    return @precision if defined? @precision
    @number_formats = Lookup.number_formats if !defined? @number_formats
    if @number_formats
      @precision = @number_formats.find? { |x| x.name.parameterize.underscore == 'precision'}.value.to_i rescue nil
    end
    if @precision.nil?
      @print_settings = PrintSetting.get_precision_delimiter if !defined? @print_settings
      if @print_settings
        @precision = @print_settings.precision.to_i
      else
        @precision = 2
      end
    end
  end

  def delimiter
    return @delimiter if defined? @delimiter
    @number_formats = Lookup.number_formats if !defined? @number_formats
    if @number_formats
      @delimiter = @number_formats.find { |f| f.name.parameterize.underscore == 'delimiter'}.value.gsub(/\\u(\h{4})/) { |m| [$1].pack("H*").unpack("n*").pack("U*") } rescue nil
    end
    if @delimiter.nil?
      @print_settings = PrintSetting.get_precision_delimiter if !defined? @print_settings
      if @print_settings && @print_settings.delimiter
        @delimiter = ","
      else
        @delimiter = ","
      end
    end
  end

  def strip_insignificant_zeros
    return @strip_insignificant_zeros if defined? @strip_insignificant_zeros
    @number_formats = Lookup.number_formats if !defined? @number_formats
    if @number_formats
      @strip_insignificant_zeros = @number_formats.find { |f| f.name.parameterize.underscore == 'strip_insignificant_zeros'}.value.in? ['1', 't', 'true', 'on', 'y', 'yes'] rescue false
    end
  end

	def number_format(number, options = {})
    options[:precision] = options[:precision] || precision
		# options[:delimiter] = options[:delimiter] || delimiter
		options[:strip_insignificant_zeros] = options[:strip_insignificant_zeros] || strip_insignificant_zeros

    number = number.to_f.round(options[:precision])

		if options[:precision] > 0
			if options[:strip_insignificant_zeros]
				formatted = "%.12g" % number
			else
				formatted = "%.#{options[:precision]}f" % number
			end
		else
			formatted = number.to_i.to_s
		end

		if options[:delimiter] && !options[:delimiter].empty?
			formatted = formatted.gsub(/(\d)(?=\d{3}+(\.\d*)?$)/, "\\1#{options[:delimiter]}")
		end

		return formatted
	end

end
