class Blockchain::BalanceQuery < ApplicationQuery

  attr_reader :params, :is_current_admin_user

  def initialize(params,is_current_admin_user)
    @params = params
    @is_current_admin_user = is_current_admin_user
  end

  def call
    if is_current_admin_user
      result_list = []
      if params[:project_id].present? or params[:keyword].present?
        token_list, total_count = find_repo_with_token(params["user_id"], 1, 10000)
        p_ids = []
        token_list.each do |t|
          p_ids.push(t['token_name'].to_i)
        end
        project_ids = params[:project_id].present? ? [params[:project_id]] : Project.where(id: p_ids).like(params[:keyword]).ids
        project_ids.each do |project_id|
          project_balance  = find_one_balance_with_token(params["user_id"], project_id)
          next if project_balance == 0
          project = Project.find_by(id: project_balance['token_name'].to_i)
          if project.present?
            owner = User.find_by(id: project.user_id)
            if owner.present?
              result_list << {project: project, balance: project_balance['balance']}
            end
          end
        end
        {"status": 0, "projects": result_list, "total_count": result_list.size}
      else
        token_list, total_count = find_repo_with_token(params["user_id"], (params["page"] || 1), (params["limit"] || 10))
        token_list.each do |t|
          project = Project.find_by(id: t['token_name'].to_i)
          if project.nil?
            result_list << {project: nil, balance: t['balance']}
            next
          end
          owner = User.find_by(id: project.user_id)
          if owner.nil? || project.nil?
          else
            balance = t['balance']
            result_list << {project: project, balance: balance}
          end
        end
        {"status": 0, "projects": result_list, "total_count": total_count}
      end
    else
      {"status": 1} # query failed
    end
  end
end
