package ch.sahits.game.graphic.display.dialog;
import ch.sahits.game.graphic.display.model.ICityPlayerProxy;
import ch.sahits.game.openpatrician.model.building.ITradingOffice;
import ch.sahits.game.openpatrician.model.product.IWare;
/**
* This action handles the buying of wares from the city and storing them in the storage
* @author Andi Hotz, (c) Sahits GmbH, 2011
* Created on Dec 24, 2011
*
*/
class City2StorageAction implements Runnable {
private final IWare ware;
private final ITransferable dialog;
// private static final Logger logger = Logger.getLogger(City2StorageAction.class);
public City2StorageAction(IWare ware, ITransferable dialog) {
super();
this.ware = ware;
this.dialog=dialog;
}
@Override
public void run() {
ICityPlayerProxy city = dialog.getCityPlayerProxy();
int availableAmountCity = city.getCity().getWare(ware).getAmount();
ITradingOffice office = city.getPlayer().findTradingOffice(city.getCity());
if (availableAmountCity>0 && office!=null){
int amount2Move = dialog.getAmount(availableAmountCity); // This is ware specific size
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 = office.move(ware, amount2Move,avgPrice);
city.getPlayer().updateCash(-avgPrice*loaded);
}
}
}