class Api::V1::Issues::IssueTagsController < Api::V1::BaseController 
  before_action :require_login, except: [:index, :pm_index]
  before_action :require_public_and_member_above, only: [:index] 
  before_action :require_operate_above, only: [:create, :update, :destroy]

  def index 
    @issue_tags = @project.issue_tags.reorder("#{sort_by} #{sort_direction}")
    @issue_tags = @issue_tags.ransack(name_cont: params[:keyword]).result if params[:keyword].present?
    if params[:only_name]
      @issue_tags = kaminary_select_paginate(@issue_tags.select(:id, :name, :color)) 
    else 
      @issue_tags = kaminari_paginate(@issue_tags.includes(:project, :user, :issue_issues, :pull_request_issues))
    end
  end

  def create
    @issue_tag = @project.issue_tags.new(issue_tag_params)
    if @issue_tag.save!
      render_ok 
    else 
      render_error("创建标记失败！")
    end
  end

  before_action :load_issue_tag, only: [:update, :destroy]

  def update 
    @issue_tag.attributes = issue_tag_params
    if @issue_tag.save! 
      render_ok 
    else 
      render_error("更新标记失败！")
    end
  end

  def destroy 
    if @issue_tag.destroy! 
      render_ok
    else 
      render_error("删除标记失败！")
    end
  end


  private 
  def sort_by
    sort_by = params.fetch(:sort_by, "created_at")
    sort_by = IssueTag.column_names.include?(sort_by) ? sort_by : "created_at"
    sort_by
  end

  def sort_direction 
    sort_direction = params.fetch(:sort_direction, "desc").downcase
    sort_direction = %w(desc asc).include?(sort_direction) ? sort_direction : "desc"
    sort_direction
  end

  def issue_tag_params 
    params.permit(:name, :description, :color)
  end

  def load_issue_tag 
    @issue_tag = @project.issue_tags.find_by_id(params[:id])
  end
end