class Metapurse < ActiveRecord::Base
  belongs_to :user, optional: true
  def icpswap_pool_data_raw
    icpswap_pool_data_raw = `dfx --identity anonymous canister --network=ic call ggzvv-5qaaa-aaaag-qck7a-cai getAllPools`
  end

  def icp_usd
    JSON.parse(`curl -s https://www.binance.com/api/v3/avgPrice?symbol=ICPUSDT`)["price"].to_f
  end

  def icp_canister_id 
    "ryjl3-tyaaa-aaaaa-aaaba-cai"
  end

  def total_usd
    total_usd = 0.0
    self.data.each_line do |record|
      canister_id = record.split[0]
      amount = record.split[1].gsub(",","").to_f # rescue nil
      if canister_id == icp_canister_id
        value = self.icp_usd
        value_amount = (value * amount).round(2) # rescue 0
        total_usd +=  value_amount # rescue 0
      else
        value = icpswap_pool_data_raw.split("record {").select{|pool| !pool.scan(canister_id).empty? && !pool.scan(icp_canister_id).empty? }[0].scan(/token0Price = [+-]?([1-9]\d*|0)(\.\d+)?/).join.to_f # rescue nil
        value_amount = (value * amount).round(2) # rescue 0
        total_usd +=  value_amount # rescue 0
      end
    end
    return total_usd.round(2)
  end

end
