class Users::OrganizationsController < Users::BaseController

  def index
    if current_user.logged?
      logged_organizations_sql = observed_user.organizations.with_visibility(%w(common limited)).to_sql
      privacy_organizations_sql = observed_user.organizations.with_visibility("privacy").joins(:organization_users).where(organization_users: {user_id: current_user.id}).to_sql
      @organizations = Organization.from("( #{ logged_organizations_sql } UNION #{ privacy_organizations_sql } ) AS users")
    else
      @organizations = observed_user.organizations.with_visibility("common")
    end

    @organizations = @organizations.ransack(login_or_nickname_cont: params[:search]).result if params[:search].present?

    @home_top_ids = @organizations.joins(:home_top_settings).where(home_top_settings: {user_id: observed_user.id}).order("home_top_settings.created_at asc").pluck(:id)

    if @home_top_ids.present?
      @organizations = @organizations.joins(:organization_extension).order("FIELD(users.id, #{@home_top_ids.join(",")}) desc, organization_extensions.#{sort_by} #{sort_direction}")
    else
      @organizations = @organizations.joins(:organization_extension).order("organization_extensions.#{sort_by} #{sort_direction}")
    end

    @organizations = kaminari_paginate(@organizations)
  end

  private
  def sort_by
    OrganizationExtension.column_names.include?(params[:sort_by]) ? params[:sort_by] : 'created_at' 
  end

  def sort_direction
    %w(desc asc).include?(params[:sort_direction]) ? params[:sort_direction] : 'desc'  
  end
end