module BlockedIps
  class ItemsController < BlockedIps::BaseController
    def index
      if params[:item] && params[:item][:ip]
        set_item
        flash[:error] = @item.errors.full_messages.to_sentence
      else
        authorize Item
      end
    end

    def create
      @item = Item.new item_params
      authorize @item

      if @item.save
        flash[:success] = "Successfuly blocked"
        @item.is_blocked = true
        # TODO: remove this assignment once IPBlock service returns the
        # remaining block time IsBlockedIP endpoint
        @item.duration = nil
      else
        flash.now[:error] = @item.errors.full_messages.to_sentence
      end
      render :index
    end

    def destroy
      set_item

      if @item.destroy
        flash[:success] = "Successfuly unblocked"
        @item.is_blocked = false
      else
        flash[:error] = @item.errors.full_messages.to_sentence
      end
      render :index
    end

    protected

    def set_item
      @item = Item.find params[:item]
      authorize @item
    end

    def item_params
      item_params = params[:item]
      if item_params[:duration]
        if item_params[:duration].empty?
          item_params[:duration] = nil
        else
          item_params[:duration] = item_params[:duration].to_i
        end
      end
      item_params
    end
  end
end
