class ItemBankQuery < ApplicationQuery
  include CustomSortable
  attr_reader :params

  sort_columns :updated_at, default_by: :updated_at, default_direction: :desc, default_table: 'item_banks'

  def initialize(params)
    @params = params
  end

  def call
    if params[:public].to_i == 1
      items = ItemBank.where(public: 1)
    elsif params[:public].to_i == 0
      items = ItemBank.where(user_id: User.current.id)
    end

    if params[:tag_discipline_id].present?
      items = items.joins(:tag_discipline_containers).where(tag_discipline_containers: {tag_discipline_id: params[:tag_discipline_id]})
    elsif params[:sub_discipline_id].present?
      items = items.where(sub_discipline_id: params[:sub_discipline_id])
    elsif params[:discipline_id].present?
      items = items.joins(:sub_discipline).where(sub_disciplines: {discipline_id: params[:discipline_id]})
    end

    if params[:oj_status].present? && params[:item_type] == "PROGRAM"
      items = items.joins("join hacks on hacks.id=item_banks.container_id and item_banks.container_type='Hack'").where(hacks: {status: params[:oj_status]})
    end

    items = items.where(item_type: params[:item_type]) if params[:item_type].present?
    items = items.where(difficulty: params[:difficulty].to_i) if params[:difficulty].present?

     if params[:keyword].present?
       sql = "left join item_choices on item_choices.item_bank_id = item_banks.id " +
           "left join hacks on hacks.id=item_banks.container_id and item_banks.container_type='Hack'"
       search_sql = "item_banks.name like :keyword or item_choices.choice_text like :keyword or hacks.description like :keyword"
       Rails.logger.info("sql_search: #{ items.joins(sql).where(search_sql, keyword: "%#{params[:keyword]}%").to_sql}")
       items = items.joins(sql).where(search_sql, keyword: "%#{params[:keyword]}%").distinct
     end

    custom_sort(items, params[:sort_by], params[:sort_direction])
  end
end