Episodes
class ItemsController < ApplicationController
  before_action :authenticate_user!
  before_action :set_list
  before_action :set_column
  before_action :set_item, only: [:edit, :update, :destroy]

  def new
    @item = @column.items.new
  end

  def edit
  end

  def create
    @item = @column.items.new(item_params)

    if @item.save
      ListChannel.broadcast_to(@list, type: 'create',
                                      item: ItemsController.render(@item, locals: { list: @list, column: @column }),
                                      column_id: @column.id)
      redirect_to @list, notice: 'Item was successfully created.'
    else
      render :new
    end
  end

  def update
    params[:positions].uniq.each_with_index do |id, index|
      @list.items.find(id).update(position: index + 1)
    end
    if @item.update(item_params)
      ListChannel.broadcast_to(@list, type: "update",
                                      column_id: @column.id,
                                      column: ItemsController.render(@column.items.order(position: :asc),
                                                locals: { list: @list, column: @column }))
      new_column_items = @list.columns.find(params[:item][:column_id]).items.order(position: :asc)
      ListChannel.broadcast_to(@list, type: "update",
                                      column_id: params[:item][:column_id],
                                      column: ItemsController.render(new_column_items,
                                                locals: { list: @list, column: @column }))
      respond_to do |format|
        format.html { redirect_to @list, notice: 'Item was successfully updated.' }
        format.json {}
      end
    else
      render :edit
    end
  end

  def destroy
    if @item.destroy
      ListChannel.broadcast_to(@list, type: "destroy", item_id: @item.id)
    end
    redirect_to @list, notice: 'Item was successfully destroyed.'
  end

  private

  def set_list
    @list = current_user.lists.includes(columns: :items).find(params[:list_id])
  end

  def set_column
    @column = @list.columns.find(params[:column_id])
  end

  def set_item
    @item = @list.items.find(params[:id])
  end

  def item_params
    params.require(:item).permit(:column_id, :content)
  end
end