class Token < ActiveRecord::Base
  enum standard: [:dip20, :icrc1, :unknown]
  validates :canister_id, uniqueness: true, allow_nil: true
  before_create :refresh

  def transfer_fee_to_f
    if self.transfer_fee.present? && self.decimals.present?
      return self.transfer_fee/(10.0**self.decimals)
    else
      return nil
    end
  end

  def get_holder_number
    if self.standard == "dip20"
      tokenInfo = `dfx canister --network ic call #{self.canister_id} getTokenInfo 2>&1`
      tokenInfo.lines[2].split[2]
    else
      "Get holder number coming soon."
    end
  end

  def get_token_info
    if self.standard == "dip20"
      tokenInfo = `dfx canister --network ic call #{self.canister_id} getTokenInfo 2>&1`
    else
      "Get token_info coming soon."
    end
  end

  def refresh
    metadata = `dfx canister --network ic call #{self.canister_id} icrc1_metadata 2>&1`
    if metadata.scan(/no update method/).present?
      # TODO: Use getTokenInfo instead of getMetadata
      metadata = `dfx canister --network ic call #{self.canister_id} getMetadata 2>&1`
      if metadata.scan(/no update method/).present?
        self.standard = :unknown
      else
        self.standard = :dip20

        # TODO: Use getTokenInfo instead of getMetadata
        tokenInfo = `dfx canister --network ic call #{self.canister_id} getTokenInfo 2>&1`
        self.holder_number = tokenInfo.lines[2].split[2]

        self.transfer_fee = metadata.lines[2].split[2].to_i
        self.decimals = metadata.lines[3].split[2]
        # self.owner = metadata.lines[4].split[3]
        # self.logo_url = metadata.lines[5].split("\"")[1]
        self.logo_url = tokenInfo.lines[8].split[2].split('"')[1]
        self.name = metadata.lines[6].split("\"")[1]
        self.total_supply = metadata.lines[7].split[2].to_i/(10.0**self.decimals)
        self.symbol = metadata.lines[8].split("\"")[1]
      end
    else
        self.standard = :icrc1
        self.transfer_fee = metadata.lines[2].split[7].to_i
        self.decimals = metadata.lines[5].split[7].to_i
        begin
          self.logo_url = metadata.lines[9].split("\"")[1]
        rescue
        end
        self.name = metadata.lines[3].split("\"")[3]
        total_supply = `dfx canister --network ic call #{self.canister_id} icrc1_total_supply 2>&1`
        self.total_supply = total_supply.split[0][1..-1].to_i/(10.0**self.decimals)
        self.symbol = metadata.lines[4].split("\"")[3]
    end
  end

end
