class LogsController < ApplicationController

  before_action :ensure_valid_user

  before_action :set_log, only: [:show, :update, :destroy]
  before_action :set_recipe, only: [:new, :create]
  before_action :require_recipe, only: [:new, :create]

  def index
    @logs = Log.for_user(current_user).order(date: :desc).page(params[:page]).per(params[:per])
    render json: LogSummarySerializer.for(@logs, collection_name: 'logs')
  end

  def show
    ensure_owner(@log)
    render json: LogSerializer.for(@log)
  end

  def edit
    ensure_owner(@log)
    render json: LogSerializer.for(@log)
  end

  def update
    ensure_owner(@log) do
      if @log.update(log_params)
        render json: { success: true }
      else
        render json: @log.errors, status: :unprocessable_entity
      end
    end
  end

  def new
    @log = Log.new
    @log.date = Time.now
    @log.user = current_user
    @log.source_recipe = @recipe
    @log.recipe = @recipe.log_copy(current_user)
  end

  def create
    @log = Log.new
    @log.assign_attributes(log_params)
    @log.recipe.is_log = true
    @log.recipe.user = current_user
    @log.user = current_user
    @log.source_recipe = @recipe

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

  def destroy
    ensure_owner(@log) do
      @log.destroy
      redirect_to logs_url, notice: 'Log Entry was successfully destroyed.'
    end
  end

  private

  def set_log
    @log = Log.includes({recipe: {recipe_ingredients: {food: :food_units} }}).find(params[:id])
  end

  def set_recipe
    if params[:recipe_id].present?
      @recipe = Recipe.includes([{recipe_ingredients: [:food]}]).find(params[:recipe_id])
    end
  end

  def require_recipe
    unless @recipe
      raise ActiveRecord::RecordNotFound
    end
  end

  def log_params
    params.require(:log).permit(:date, :rating, :notes, recipe_attributes: [:name, :description, :source, :yields, :total_time, :active_time, :step_text, recipe_ingredients_attributes: [:name, :ingredient_id, :quantity, :units, :preparation, :sort_order, :id, :_destroy]])
  end

end