class CalculatorController < ApplicationController

  def index

  end

  def calculate
    input = params[:input]
    output_unit = params[:output_unit]
    density = params[:density]
    density = nil unless density.present?

    data = {errors: [], output: ''}

    begin
      unit = UnitConversion.parse(input)
      if output_unit.present?
        unit = unit.convert(output_unit, density)
        data[:output] = unit.to_s
      else
        data[:output] = unit.auto_unit.to_s
      end

    rescue UnitConversion::UnparseableUnitError => e
      data[:errors] << e.message
    end

    render json: data
  end

  def ingredient_search
    @ingredients = Ingredient.has_density.search(params[:query]).order(:name)
  end

end