class Organizations::IsPinnedProjectsController < Organizations::BaseController
  before_action :load_organization

  def index
    @is_pinned_projects = @organization.pinned_projects.left_joins(project: :license)
                                       .where("licenses.is_secret = TRUE OR projects.is_public = TRUE")
                                       .order(position: :desc, created_at: :asc)
                                       .includes(project: [:project_category, :project_language, :repository]).order(position: :desc)
    @is_pinned_projects = kaminari_paginate(@is_pinned_projects)
  end

  def pin
    project_ids = params[:is_pinned_project_ids] || []
    @organization.is_pinned_project_ids = project_ids

    render_ok
  rescue ActiveRecord::RecordNotFound => e
    render_not_found
  rescue Exception => e
    uid_logger_error(e.message)
    tip_exception(e.message)
  end

  def update
    @pinned_project = PinnedProject.find_by_id(params[:id])
    @pinned_project.attributes = pinned_project_params
    if @pinned_project.save
      render_ok
    else
      render_error
    end
  rescue Exception => e
    uid_logger_error(e.message)
    tip_exception(e.message)
  end

  private

  def load_organization
    @organization = Organization.find_by(login: params[:organization_id]) || Organization.find_by(id: params[:organization_id])
    return render_not_found("组织不存在") if @organization.nil?
    return render_forbidden("没有查看组织的权限") if org_limited_condition || org_privacy_condition
  end

  # def is_pinned_project_ids
  #   if params[:is_pinned_project_ids].present?
  #     return params[:is_pinned_project_ids].select { |id| @organization.full_member_projects.visible.pluck(:id).include?(id.to_i) }
  #   end
  #   if params[:is_pinned_project_id].present?
  #     return @organization.is_pinned_project_ids unless @organization.full_member_projects.visible.pluck(:id).include?(params[:is_pinned_project_id].to_i)
  #     return @organization.is_pinned_project_ids.include?(params[:is_pinned_project_id].to_i) ? @organization.is_pinned_project_ids : @organization.is_pinned_project_ids.push(params[:is_pinned_project_id].to_i)
  #   end
  # end

  def pinned_project_params
    params.require(:pinned_project).permit(:position)
  end

end