module Keys
  class BatchesController < Keys::BaseController
    def index
      authorize Batch

      @batch = Batch.new
      @batch_id = SecureRandom.uuid

      @batches = []
      unless params[:pool_id].present?
        flash[:error] = 'Pool ID is required'
        return
      end

      @pool_id = params[:pool_id]

      cursor = ''
      if params[:cursor].present?
        cursor = params[:cursor]
      end

      resp = Batch.all(@pool_id, cursor, current_user.ldap_login)
      unless resp.success? && resp.status == 200
        flash[:error] = 'Error loading key batches'
        return
      end

      unless resp.body['key_batches'].nil?
        @batches = resp.body['key_batches']
      end
      @cursor = resp.body['cursor']
    end

    def create
      authorize Batch

      @batch = Batch.new
      permitted = params.require(:keys_batch).permit(:pool_id, :batch_id, :number_of_keys).merge(ldap_login: current_user.ldap_login)
      @batch.attributes = permitted

      resp = @batch.create
      unless resp.success? && resp.status == 200
        flash[:error] = 'Error creating batch'
        return redirect_back
      end

      flash[:success] = 'Successfully created batch'

      redirect_back
    end

    def deactivate
      authorize Batch

      permitted = params.permit(:batch_id).merge(ldap_login: current_user.ldap_login)
      @batch = Batch.from_attributes(permitted)
      resp = @batch.update_status('INACTIVE')

      unless resp.success? && resp.status == 200
        flash[:error] = 'Error deactivating batch'
        return redirect_back
      end

      flash[:success] = 'Successfully deactivated batch'

      redirect_back
    end

    def activate
      authorize Batch

      permitted = params.permit(:batch_id).merge(ldap_login: current_user.ldap_login)
      @batch = Batch.from_attributes(permitted)
      resp = @batch.update_status('ACTIVE')

      unless resp.success? && resp.status == 200
        flash[:error] = 'Error activating batch'
        return redirect_back
      end

      flash[:success] = 'Successfully activated batch'

      redirect_back
    end
  end
end