private Money getDifferenceSum(List<AssetClass> group) {
   Money sum = MoneyFactory.fromDouble(0);
   for (AssetClass item : group) {
     sum.add(item.getDifference());
   }
   return sum;
 }
 private Money getCurrentAllocationSum(List<AssetClass> group) {
   Money sum = MoneyFactory.fromDouble(0);
   for (AssetClass item : group) {
     sum.add(item.getCurrentAllocation());
   }
   return sum;
 }
  private Money calculateCurrentValue(List<AssetClass> allocations) {
    Money result = MoneyFactory.fromDouble(0);

    for (AssetClass ac : allocations) {
      Money itemValue;

      ItemType type = ac.getType();
      switch (type) {
        case Group:
          // Group. Calculate for children.
          itemValue = calculateCurrentValue(ac.getChildren());
          break;

        case Allocation:
          // Allocation. get value of all stocks.
          itemValue = sumStockValues(ac.getStocks());
          break;

        case Cash:
          itemValue = ac.getValue();
          break;

        default:
          ExceptionHandler handler = new ExceptionHandler(getContext());
          handler.showMessage("encountered an item with no type set!");
          itemValue = MoneyFactory.fromDouble(0);
          break;
      }

      ac.setCurrentValue(itemValue);
      result = result.add(itemValue);
    }

    return result;
  }
  /**
   * Add Cash as a separate, automatic asset class that uses all the cash amounts from the
   * investment accounts.
   *
   * @param assetAllocation Main asset allocation object.
   */
  private void addCash(AssetClass assetAllocation) {
    // get all investment accounts, their currencies and cash balances.
    AccountRepository repo = new AccountRepository(getContext());
    AccountService accountService = new AccountService(getContext());
    List<String> investmentAccounts = new ArrayList<>();
    investmentAccounts.add(AccountTypes.INVESTMENT.toString());
    CurrencyService currencyService = new CurrencyService(getContext());
    int destinationCurrency = currencyService.getBaseCurrencyId();
    Money zero = MoneyFactory.fromDouble(0);

    List<Account> accounts = accountService.loadAccounts(false, false, investmentAccounts);

    Money sum = MoneyFactory.fromDouble(0);

    // Get the balances in base currency.
    for (Account account : accounts) {
      int sourceCurrency = account.getCurrencyId();
      Money amountInBase =
          currencyService.doCurrencyExchange(
              destinationCurrency, account.getInitialBalance(), sourceCurrency);
      sum = sum.add(amountInBase);
    }

    // add the cash asset class
    // todo: the allocation needs to be editable!
    AssetClass cash = AssetClass.create(getContext().getString(R.string.cash));
    cash.setType(ItemType.Cash);
    cash.setAllocation(zero);
    cash.setCurrentAllocation(zero);
    cash.setDifference(zero);
    cash.setValue(sum);

    assetAllocation.addChild(cash);
  }
  private void updateAllocation() {
    View view = getView();
    if (view == null) return;

    TextView textView = (TextView) view.findViewById(R.id.allocationEdit);
    if (textView != null) {
      Money allocation = assetClass.getAllocation();
      // FormatUtilities.formatAmountTextView();
      textView.setText(allocation.toString());
      textView.setTag(allocation.toString());
    }
  }
  private Money getAllocationSum(List<AssetClass> group) {
    List<Money> allocations = new ArrayList<>();
    for (AssetClass item : group) {
      allocations.add(item.getAllocation());
    }

    Money sum = MoneyFactory.fromString("0");
    for (Money allocation : allocations) {
      sum = sum.add(allocation);
    }
    return sum;
  }
  /**
   * The magic happens here. Calculate all dependent variables.
   *
   * @param totalPortfolioValue The total value of the portfolio, in base currency.
   */
  private void calculateStatsFor(AssetClass item, Money totalPortfolioValue) {
    Money zero = MoneyFactory.fromString("0");
    if (totalPortfolioValue.toDouble() == 0) {
      item.setValue(zero);
      item.setCurrentAllocation(zero);
      item.setCurrentValue(zero);
      item.setDifference(zero);
      return;
    }

    // Set Value
    Money allocation = item.getAllocation();
    // value = allocation * totalPortfolioValue / 100;
    Money value =
        totalPortfolioValue
            .multiply(allocation.toDouble())
            .divide(100, Constants.DEFAULT_PRECISION);
    item.setValue(value);

    // current value
    Money currentValue = sumStockValues(item.getStocks());
    item.setCurrentValue(currentValue);

    // Current allocation.
    Money currentAllocation =
        currentValue
            .multiply(100)
            .divide(totalPortfolioValue.toDouble(), Constants.DEFAULT_PRECISION);
    item.setCurrentAllocation(currentAllocation);

    // difference
    Money difference = currentValue.subtract(value);
    item.setDifference(difference);
  }
  private Money sumStockValues(List<Stock> stocks) {
    Money sum = MoneyFactory.fromString("0");
    CurrencyService currencyService = new CurrencyService(getContext());
    AccountRepository repo = new AccountRepository(getContext());
    int baseCurrencyId = currencyService.getBaseCurrencyId();

    for (Stock stock : stocks) {
      // convert the stock value to the base currency.
      int accountId = stock.getHeldAt();
      int currencyId = repo.loadCurrencyIdFor(accountId);
      Money value =
          currencyService.doCurrencyExchange(baseCurrencyId, stock.getValue(), currencyId);

      sum = sum.add(value);
    }
    return sum;
  }
  public int saveExchangeRate(int currencyId, Money exchangeRate) {
    ContentValues contentValues = new ContentValues();
    contentValues.put(TableCurrencyFormats.BASECONVRATE, exchangeRate.toString());

    int result =
        mContext
            .getContentResolver()
            .update(
                mCurrencyTable.getUri(),
                contentValues,
                TableCurrencyFormats.CURRENCYID + "=?",
                new String[] {Integer.toString(currencyId)});

    return result;
  }
 protected void setMoney(String fieldName, Money value) {
   contentValues.put(fieldName, value.toString());
 }