class OptionalItemQuery < ApplicationQuery
  attr_reader :sub_discipline_id, :tag_discipline_id, :difficulty, :source

  def initialize(sub_discipline_id, tag_discipline_id, difficulty, source)
    @sub_discipline_id = sub_discipline_id
    @tag_discipline_id = tag_discipline_id
    @difficulty = difficulty
    @source = source
  end

  def call
    items = ItemBank.all
    if tag_discipline_id.present? && sub_discipline_id.present?
      items = items.joins(:tag_discipline_containers).where(tag_discipline_containers: {tag_discipline_id: tag_discipline_id})
      hacks = Hack.joins(:tag_discipline_containers).where(tag_discipline_containers: {tag_discipline_id: tag_discipline_id})
    elsif sub_discipline_id.present?
      items = items.where(sub_discipline_id: sub_discipline_id)
      hacks = Hack.where(sub_discipline_id: sub_discipline_id)
    end

    if hacks.present?
      items = ItemBank.where(container_id: hacks.where(status: 1).pluck(:id), container_type: "Hack")
                .or(ItemBank.where(id: items.pluck(:id)).where("item_type != '6'"))
    end

    public = source.present? ? source.to_i : 1
    if public == 1
      items = items.where(public: 1)
    elsif public == 0
      items = items.where(user_id: User.current.id)
    end

    # 难度
    diff = difficulty ? difficulty.to_i : 1
    items = items.where(difficulty: diff)
    items
  end
end