class ApplicationQuery
  include Callable

  private

  def strip_param(key)
    params[key].to_s.strip.presence
  end

  # find all the repos that a user has tokens
  def find_repo_with_token(user_id, page=1, limit=10)
    params = {
      "request-type": "query user balance of all repos by page",
      "username": user_id.to_s, 
      "page": page.to_i, 
      "page_num": limit.to_i
    }.to_json
    resp_body = Blockchain::InvokeBlockchainApi.call(params)
    if resp_body['status'] != 0
      raise "区块链接口请求失败."
    else
      token_list = resp_body['UserBalanceList'].nil? ? [] : resp_body['UserBalanceList']
      return token_list, resp_body['total_count']
    end
  end

  # find one repo that a user has tokens
  def find_one_balance_with_token(user_id, project_id)
    # return 3 statuses: UnknownErr/ResUserNotExisted/Success
    params = {
      "request-type": "query user balance of single repo",
      "username": user_id.to_s,
      "token_name": project_id.to_s
    }.to_json
    Rails.logger.info "query user balance of single repo params======= #{params}"
    resp_body = Blockchain::InvokeBlockchainApi.call(params)
    Rails.logger.info "resp_body======= #{resp_body}"
    if resp_body['status'] == 0
      return resp_body
    elsif resp_body['status'] == 100
      return 0 # 找不到用户返回0
    else
      raise "区块链接口请求失败."
    end
  end


  # find one repo that a user has tokens
  def find_one_balance(user_id, project_id)
    # return 3 statuses: UnknownErr/ResUserNotExisted/Success
    params = {
      "request-type": "query user balance of single repo",
      "username": user_id.to_s,
      "token_name": project_id.to_s
    }.to_json
    resp_body = Blockchain::InvokeBlockchainApi.call(params)
    if resp_body['status'] == 0
      return resp_body['balance']
    elsif resp_body['status'] == 100
      return 0 # 找不到用户返回0
    else
      raise "区块链接口请求失败."
    end
  end

  # query the basic info of a repository
  def find_blockchain_repo_info(project_id)
    params = {
      "request-type": "query repo basic info",
      "token_name": project_id.to_s
    }.to_json
    resp_body = Blockchain::InvokeBlockchainApi.call(params)
    if resp_body['status'] == 0
      return resp_body
    else
      raise "区块链接口请求失败."
    end
  end

end