class RecipesController < ApplicationController

  before_action :set_recipe, only: [:show, :update, :destroy]

  before_action :ensure_valid_user, except: [:show, :index]

  # GET /recipes
  def index
    @criteria = ViewModels::RecipeCriteria.new(criteria_params)
    @recipes = Recipe.for_criteria(@criteria).includes(:tags)
    render json: RecipeSummarySerializer.for(@recipes, collection_name: 'recipes')
  end

  # GET /recipes/1
  # GET /recipes/1.json
  def show
    if params[:scale].present?
      @scale = params[:scale]
      @recipe.scale(params[:scale], true)
    end

    if params[:system].present?
      @system = params[:system]
      case @system
        when 'metric'
          @recipe.convert_to_metric
        when 'standard'
          @recipe.convert_to_standard
      end
    end

    if params[:unit].present?
      @unit = params[:unit]
      case @unit
        when 'mass'
          @recipe.convert_to_mass
        when 'volume'
          @recipe.convert_to_volume
      end
    end

    render json: RecipeSerializer.for(@recipe)
  end

  # POST /recipes
  def create
    @recipe = Recipe.new(recipe_params)
    @recipe.user = current_user

    if @recipe.save
      render json: { id: @recipe.id }
    else
      render json: @recipe.errors, status: :unprocessable_entity
    end
  end

  # PATCH/PUT /recipes/1
  def update
    ensure_owner(@recipe) do
      # Merge in updated_at to force the record to be dirty (in case only tags were changed)
      if @recipe.update(recipe_params.merge(updated_at: Time.now))
        render json: { success: true }
      else
        render json: @recipe.errors, status: :unprocessable_entity
      end
    end
  end

  # POST /recipes/preview_steps
  def preview_steps
    render json: { rendered_steps: MarkdownProcessor.render(params[:step_text]) }
  end

  # DELETE /recipes/1
  def destroy
    ensure_owner(@recipe) do
      @recipe.deleted = true
      @recipe.save!(validate: false)

      render json: { success: true }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_recipe
      @recipe = Recipe.includes(recipe_ingredients: [{food: :food_units }, {recipe_as_ingredient: {recipe_ingredients: {food: :food_units }}}]).find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def recipe_params
      params.require(:recipe).permit(:name, :description, :source, :yields, :total_time, :active_time, :step_text, :is_ingredient, tag_names: [], recipe_ingredients_attributes: [:name, :ingredient_id, :quantity, :units, :preparation, :sort_order, :id, :_destroy])
    end

    def criteria_params
      params.require(:criteria).permit(*ViewModels::RecipeCriteria::PARAMS)
    end
end
