class Action::NodeInputsController < ApplicationController
  before_action :require_admin, except: [:index]
  before_action :find_action_node

  def index
    @node_inputs = @node.action_node_inputs
    respond_to do |format|
      format.html
      format.json{ render_ok(data: @node_inputs.as_json) }
    end
  end

  def create
    @node_input = Action::NodeInput.new(node_input_params)
    @node_input.action_node = @node
    respond_to do |format|
      if @node_input.save
        format.html { redirect_to action_node_node_inputs_path(@node), notice: '创建成功.' }
        format.json { render_ok(data: @node_input.as_json) }
      else
        format.html { render :new }
        format.json { render json: @node_input.errors, status: -1 }
      end
    end
  end

  def new

  end

  def show

  end

  def edit

  end

  def update
    @node_input.update(node_input_params)
    respond_to do |format|
      format.html { redirect_to action_node_node_inputs_path(@node), notice: '更新成功.' }
      format.json { render_ok(data: @node_input.as_json) }
    end
  end

  def destroy
    if @node_input.destroy!
      flash[:success] = '删除成功'
    else
      flash[:danger] = '删除失败'
    end
    respond_to do |format|
      format.html { redirect_to "api/actions/nodes" }
      format.json { render_ok() }
    end
  end

  private

  def find_action_node
    @node = Action::Node.find(params[:node_id])
    if params[:id].present?
      @node_input = @node.action_node_inputs.find(params[:id])
    else
      @node_input = Action::NodeInput.new
    end

  end

  def node_input_params
    if params.require(:action_node_input)
      params.require(:action_node_input).permit(:name, :input_type, :description, :is_required, :sort_no, :default_value)
    else
      params.permit(:name, :input_type, :description, :is_required, :sort_no, :default_value)
    end
  end
end
