class Action::NodesController < ApplicationController
  # before_action :require_admin, except: [:index]
  before_action :require_login
  before_action :find_action_node, except: [:index, :create, :new]

  def index
    @node_types = Action::NodeType.all
    no_node_type = Action::NodeType.find_by(name: "未分类")
    @no_type_nodes = Action::Node.where(action_node_types_id: nil)
    @no_type_nodes = Action::Node.where(action_node_types_id: nil).or(Action::Node.where(action_node_types_id: no_node_type.id)) if no_node_type.present?
    respond_to do |format|
      format.html { @nodes = Action::Node.where("name LIKE :search OR full_name LIKE :search", :search => "%#{params[:search]}%") }
      format.json
    end
  end

  def create
    @node = Action::Node.new(node_params)
    if params.require(:node).present? && params.require(:node)[:link_type_array].present?
      @node.link_type = (params.require(:node)[:link_type_array] - [""]).join(",")
    end
    @node.user_id = current_user.id
    respond_to do |format|
      if @node.save
        format.html { redirect_to action_nodes_path, notice: '创建成功.' }
        format.json { render_ok(data: @node.as_json) }
      else
        format.html { render :new }
        format.json { render json: @node.errors, status: -1 }
      end
    end
  end

  def new
    @node = Action::Node.new
  end

  def show

  end

  def edit
    if @node.link_type.present?
      @node.link_type_array = @node.link_type.to_s.split(",")
    end
  end

  def update
    if params.require(:node).present?  && params.require(:node)[:link_type_array].present?
      @node.link_type = (params.require(:node)[:link_type_array] - [""]).join(",")
    end
    @node.user_id = current_user.id if @node.user_id.blank?
    @node.update(node_params)
    respond_to do |format|
      format.html { redirect_to action_nodes_path, notice: '更新成功.' }
      format.json { render_ok(data: @node.as_json) }
    end
  end

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

  private

  def find_action_node
    @node = Action::Node.find(params[:id])
  end

  def node_params
    if params.require(:action_node)
      params.require(:action_node).permit(:name, :label, :full_name, :description, :icon, :action_node_types_id,
                                          :is_local, :local_url, :yaml, :sort_no, :node_type, :is_mutil_link, :link_type, :link_type_array)
    else
      params.permit(:name, :label, :full_name, :description, :icon, :action_node_types_id, :is_local, :local_url,
                    :yaml, :sort_no, :node_type, :is_mutil_link, :link_type, :link_type_array)
    end
  end
end
