class CalculatorController < ApplicationController

  def index

  end

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

    if ingredient_id.present?
      ingredient = Ingredient.find_by_ingredient_id(ingredient_id)
    end

    data = {errors: Hash.new { |h, k| h[k] = [] }, output: ''}

    UnitConversion::with_custom_units(ingredient ? ingredient.custom_units : []) do
      density_unit = nil
      begin
        if density
          density_unit = UnitConversion.parse(density)
          unless density_unit.density?
            data[:errors][:density] << 'not a density unit'
            density_unit = nil
          end
        end
      rescue UnitConversion::UnparseableUnitError => e
        data[:errors][:density] << 'invalid string'
      end

      begin
        input_unit = UnitConversion.parse(input)
        input_unit.unitwise
      rescue UnitConversion::UnparseableUnitError => e
        data[:errors][:input] << e.message
        input_unit = nil
      end

      if !input_unit.nil?
        if output_unit.present?
          begin
            input_unit = input_unit.convert(output_unit, density_unit)
          rescue UnitConversion::UnparseableUnitError => e
            data[:errors][:output_unit] << e.message
          end
        else
          input_unit = input_unit.auto_unit
        end
      end

      if data[:errors].empty?
        data[:output] = input_unit.to_s
      end
    end

    render json: data
  end

  def ingredient_search
    @foods = Food.has_density.search(params[:query]).order(:name)
    render json: @foods.map { |f| {id: f.id, name: f.name, density: f.density} }
  end

end