this.dialog=dialog;
}
@Override
public void run() {
ICityPlayerProxy city = dialog.getCityPlayerProxy();
int availableAmountCity = city.getCity().getWare(ware).getAmount();
if (availableAmountCity>0){
int amount2Move = dialog.getAmount(availableAmountCity); // This is ware specific size
// consider available capacity
final short sizeAsBarrels = ware.getSizeAsBarrels();
if (sizeAsBarrels==1){
amount2Move = Math.min(amount2Move, city.getActiveShip().getCapacity());
} else {
int temp = Math.min(amount2Move*sizeAsBarrels, city.getActiveShip().getCapacity());
amount2Move = temp/sizeAsBarrels;
}
int avgPrice = ware.computeBuyPrice(availableAmountCity, amount2Move);
// check if this is afforable
final long cash = city.getPlayer().getCompany().getCash();
if (cash<(long)avgPrice*amount2Move){
int amountAprox = (int) (cash/avgPrice); // approx amount we can afford
if (amountAprox>0){
int tempPrice = ware.computeBuyPrice(availableAmountCity, amountAprox);
while (amountAprox*tempPrice+tempPrice<cash){
int newTempPrice = ware.computeBuyPrice(availableAmountCity, amountAprox++);
if (amountAprox*newTempPrice>cash){
// we cannot afford another item
break;
}
tempPrice=newTempPrice;
}
avgPrice=tempPrice;
amount2Move=amountAprox;
} else {
return; // cannot buy anything
}
}
int movedAmount = city.getCity().move(ware, -amount2Move,city.getPlayer());
if (amount2Move!=-movedAmount){
avgPrice = ware.computeBuyPrice(city.getCity().getWare(ware).getAmount()+movedAmount, movedAmount);
amount2Move=movedAmount;
}
int loaded = city.getActiveShip().load(ware, amount2Move, avgPrice);
city.getPlayer().updateCash(-avgPrice*loaded);
}
}