# Mixin to Cucumber World (for step defs) and page classes that need it
module MathHelper
  ## Currency helpers

  # Convert to a bigdecimal in US number format, stripping any non-digit chars,
  # while still preserving negative amount
  def currency_amount_from(string)
    string.gsub(/[^\d-]/, "").to_d / 100
  end

  # Format a big decimal to 2 decimal places
  def formatted_to_2d_precision(decimal)
    format("%.2f", decimal)
  end

  ## Period helpers
  def quarter_start_for_period(num)
    # Probably not edge case safe for numbers 0-1 but doesn't matter
    return num if num % 3 == 1
    return num - 1 if num % 3 == 2
    return num - 2 if num % 3 == 0
  end

  def quarter_end_for_period(num)
    return num if num % 3 == 0
    return num + 2 if num % 3 == 1
    return num + 1 if num % 3 == 2
  end

  def period_to_quarter_string(num)
    quarter = (((num - 1) / 3) % 4) + 1
    year = ((num - 1) / 12) + 1999
    "Q#{quarter} #{year}"
  end

  def period_to_month_string(num)
    require "date"
    month_int = num % 12
    month_int = 12 if month_int == 0 # to account for December
    month = Date::MONTHNAMES[month_int][0..2] # 1 -> "Jan", 12 -> "Dec"
    year = ((num - 1) / 12) + 1999
    "#{month} #{year}"
  end
end
