/** * Determine the cost of a given number of an item and calculate a new value for the item * accordingly. * * @param oper 1 for buying, 0 for selling. * @param commodity the commodity in question * @param amount the desired amount of the item in question * @return the total cost and the calculated new value as an Invoice */ public Invoice generateInvoice(int oper, Commodities commodity, int amount) { // get the initial value of the item, 0 for not found Invoice inv = new Invoice(0.0, 0.0); inv.value = commodity.getValue(); // get the spread so we can do one initial decrement of the value if we are selling BigDecimal spread = BigDecimal.valueOf(commodity.getSpread()); // determine the total cost inv.total = 0.0; for (int x = 1; x <= amount; x++) { BigDecimal minValue = BigDecimal.valueOf(commodity.getMinValue()); BigDecimal maxValue = BigDecimal.valueOf(commodity.getMaxValue()); BigDecimal changeRate = BigDecimal.valueOf(commodity.getChangeRate()); // work the spread on the first one. if ((oper == 0) && (x == 1)) { inv.subtractValue(spread.doubleValue()); } else if ((oper == 0) && (x > 1)) { // otherwise, do the usual decriment. inv.subtractValue(changeRate.doubleValue()); } // check the current value if (inv.getValue() >= minValue.doubleValue()) { // current value is @ or above minValue // be sure value is not above maxValue if (inv.getValue() < maxValue.doubleValue()) { // current value is "just right" inv.addTotal(inv.getValue()); // add current value to total } else { // current value is above the max inv.addTotal(maxValue.doubleValue()); // add maxValue to total } } else { // current value is below the minimum inv.addTotal(minValue.doubleValue()); // add the minimum to total if ((oper == 0) && (x == 1)) { inv.subtractTotal( spread .doubleValue()); // subtract the spread if we're selling and this is the first run } } // Change our stored value for the item // we don't care about min/maxValue here because we don't want the value to 'bounce' off of // them. if (oper == 1) { inv.addValue(changeRate.doubleValue()); } } return inv; }