class TaskItemsController < ApplicationController

  before_action :ensure_valid_user
  before_action :set_task_list
  before_action :set_task_item, only: [:update]

  def create
    @task_item = TaskItem.new(task_item_params)
    @task_item.task_list = @task_list

    if @task_item.save
      TaskChannel.update_task_list(@task_list)
      render json: TaskItemSerializer.for(@task_item), status: :created, location: [@task_list, @task_item]
    else
      render json: @task_item.errors, status: :unprocessable_entity
    end
  end

  def update
    if @task_item.update(task_item_params)
      TaskChannel.update_task_list(@task_list)
      render json: TaskItemSerializer.for(@task_item), status: :ok, location: [@task_list, @task_item]
    else
      render json: @task_item.errors, status: :unprocessable_entity
    end
  end

  def destroy
    ids = Array.wrap(params[:id]) + Array.wrap(params[:ids])
    TaskItem.transaction do
      @task_items = @task_list.task_items.find(ids)
      @task_items.each { |i| i.destroy }
    end

    TaskChannel.update_task_list(@task_list)

    head :no_content
  end

  def complete
    ids = Array.wrap(params[:id]) + Array.wrap(params[:ids])
    new_status = !params[:invert].present?
    TaskItem.transaction do
      @task_items = @task_list.task_items.find(ids)
      @task_items.each { |i| i.update_column(:completed, new_status) }
    end

    TaskChannel.update_task_list(@task_list)

    head :no_content
  end

  private

  def task_item_params
    params.require(:task_item).permit(:name, :quantity, :completed)
  end

  def set_task_list
    @task_list = TaskList.find(params[:task_list_id])
    ensure_owner(@task_list)
  end

  def set_task_item
    @task_item = @task_list.task_items.find(params[:id])
  end

end
