class Action::TemplatesController < ApplicationController
  before_action :require_admin, except: [:index]
  before_action :find_action_template, except: [:index, :create, :new]

  def index
    @templates = Action::Template.all
    respond_to do |format|
      format.html
      format.json
    end
  end

  def create
    @template = Action::Template.new(templates_params)
    respond_to do |format|
      if @template.save
        format.html { redirect_to action_templates_path, notice: '创建成功.' }
        format.json { render_ok(data: @template.as_json) }
      else
        format.html { render :new }
        format.json { render json: @template.errors, status: -1 }
      end
    end
  end

  def show

  end

  def new
    @template = Action::Template.new
  end

  def edit

  end

  def update
    @template.update(templates_params)
    respond_to do |format|
      format.html { redirect_to action_templates_path, notice: '更新成功.' }
      format.json { render_ok(data: @template.as_json) }
    end
  end

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

  private

  def find_action_template
    @template = Action::Template.find(params[:id])
  end

  def templates_params
    if params.require(:action_template)
      params.require(:action_template).permit(:name, :description, :img, :sort_no, :json, :yaml)
    else
      params.permit(:name, :description, :img, :sort_no, :json, :yaml)
    end
  end
end
