2
0

CastleManorManager.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. /*
  2. * This program is free software: you can redistribute it and/or modify it under
  3. * the terms of the GNU General Public License as published by the Free Software
  4. * Foundation, either version 3 of the License, or (at your option) any later
  5. * version.
  6. *
  7. * This program is distributed in the hope that it will be useful, but WITHOUT
  8. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  9. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  10. * details.
  11. *
  12. * You should have received a copy of the GNU General Public License along with
  13. * this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. package net.sf.l2j.gameserver.instancemanager;
  16. import java.sql.PreparedStatement;
  17. import java.sql.ResultSet;
  18. import java.util.Calendar;
  19. import java.util.concurrent.ScheduledFuture;
  20. import java.util.logging.Logger;
  21. import javolution.util.FastList;
  22. import net.sf.l2j.Config;
  23. import net.sf.l2j.L2DatabaseFactory;
  24. import net.sf.l2j.gameserver.ThreadPoolManager;
  25. import net.sf.l2j.gameserver.datatables.ClanTable;
  26. import net.sf.l2j.gameserver.model.ClanWarehouse;
  27. import net.sf.l2j.gameserver.model.ItemContainer;
  28. import net.sf.l2j.gameserver.model.L2Clan;
  29. import net.sf.l2j.gameserver.model.L2Manor;
  30. import net.sf.l2j.gameserver.model.L2World;
  31. import net.sf.l2j.gameserver.model.actor.instance.L2PcInstance;
  32. import net.sf.l2j.gameserver.model.entity.Castle;
  33. import net.sf.l2j.gameserver.network.SystemMessageId;
  34. import net.sf.l2j.gameserver.network.serverpackets.SystemMessage;
  35. import net.sf.l2j.util.Rnd;
  36. /**
  37. * Class For Castle Manor Manager Load manor data from DB Update/Reload/Delete
  38. * Handles all schedule for manor
  39. * @author l3x
  40. */
  41. public class CastleManorManager {
  42. protected static final Logger _log = Logger.getLogger(CastleManorManager.class.getName());
  43. private static CastleManorManager _instance;
  44. public static final int PERIOD_CURRENT = 0;
  45. public static final int PERIOD_NEXT = 1;
  46. private static final String CASTLE_MANOR_LOAD_PROCURE =
  47. "SELECT * FROM castle_manor_procure WHERE castle_id=?";
  48. private static final String CASTLE_MANOR_LOAD_PRODUCTION =
  49. "SELECT * FROM castle_manor_production WHERE castle_id=?";
  50. private static final int NEXT_PERIOD_APPROVE = Config.ALT_MANOR_APPROVE_TIME; // 6:00
  51. private static final int NEXT_PERIOD_APPROVE_MIN = Config.ALT_MANOR_APPROVE_MIN; //
  52. private static final int MANOR_REFRESH = Config.ALT_MANOR_REFRESH_TIME; // 20:00
  53. private static final int MANOR_REFRESH_MIN = Config.ALT_MANOR_REFRESH_MIN; //
  54. protected static final long MAINTENANCE_PERIOD = Config.ALT_MANOR_MAINTENANCE_PERIOD; // 6 mins
  55. private Calendar _manorRefresh;
  56. private Calendar _periodApprove;
  57. private boolean _underMaintenance;
  58. private boolean _disabled;
  59. protected ScheduledFuture<?> _scheduledManorRefresh;
  60. protected ScheduledFuture<?> _scheduledMaintenanceEnd;
  61. protected ScheduledFuture<?> _scheduledNextPeriodapprove;
  62. public static final CastleManorManager getInstance() {
  63. if (_instance == null) {
  64. _log.info("Initializing CastleManorManager");
  65. _instance = new CastleManorManager();
  66. }
  67. return _instance;
  68. }
  69. public class CropProcure {
  70. int _cropId;
  71. int _buyResidual;
  72. int _rewardType;
  73. int _buy;
  74. int _price;
  75. public CropProcure(int id) {
  76. _cropId = id;
  77. _buyResidual = 0;
  78. _rewardType = 0;
  79. _buy = 0;
  80. _price = 0;
  81. }
  82. public CropProcure(int id, int amount, int type, int buy, int price) {
  83. _cropId = id;
  84. _buyResidual = amount;
  85. _rewardType = type;
  86. _buy = buy;
  87. _price = price;
  88. }
  89. public int getReward() { return _rewardType; }
  90. public int getId() { return _cropId; }
  91. public int getAmount() { return _buyResidual; }
  92. public int getStartAmount() { return _buy; }
  93. public int getPrice() { return _price; }
  94. public void setAmount (int amount) { _buyResidual = amount; }
  95. }
  96. public class SeedProduction {
  97. int _seedId;
  98. int _residual;
  99. int _price;
  100. int _sales;
  101. public SeedProduction(int id) {
  102. _seedId = id;
  103. _sales = 0;
  104. _price = 0;
  105. _sales = 0;
  106. }
  107. public SeedProduction(int id, int amount, int price, int sales) {
  108. _seedId = id;
  109. _residual = amount;
  110. _price = price;
  111. _sales = sales;
  112. }
  113. public int getId() {return _seedId; }
  114. public int getCanProduce() {return _residual; }
  115. public int getPrice() {return _price; }
  116. public int getStartProduce() { return _sales; }
  117. public void setCanProduce(int amount){ _residual = amount; }
  118. }
  119. private CastleManorManager() {
  120. load(); // load data from database
  121. init(); // schedule all manor related events
  122. _underMaintenance = false;
  123. _disabled = !Config.ALLOW_MANOR;
  124. boolean isApproved = (_periodApprove.getTimeInMillis() < Calendar.getInstance().getTimeInMillis() &&
  125. _manorRefresh.getTimeInMillis() > Calendar.getInstance().getTimeInMillis());
  126. for (Castle c: CastleManager.getInstance().getCastles()) {
  127. c.setNextPeriodApproved(isApproved);
  128. }
  129. }
  130. private void load() {
  131. java.sql.Connection con = null;
  132. ResultSet rs;
  133. PreparedStatement statement;
  134. try {
  135. // Get Connection
  136. con = L2DatabaseFactory.getInstance().getConnection();
  137. for (Castle castle : CastleManager.getInstance().getCastles()) {
  138. FastList<SeedProduction> production = new FastList<SeedProduction>();
  139. FastList<SeedProduction> productionNext = new FastList<SeedProduction>();
  140. FastList<CropProcure> procure = new FastList<CropProcure>();
  141. FastList<CropProcure> procureNext = new FastList<CropProcure>();
  142. // restore seed production info
  143. statement = con.prepareStatement(CASTLE_MANOR_LOAD_PRODUCTION);
  144. statement.setInt(1, castle.getCastleId());
  145. rs = statement.executeQuery();
  146. while(rs.next()) {
  147. int seedId = rs.getInt("seed_id");
  148. int canProduce = rs.getInt("can_produce");
  149. int startProduce = rs.getInt("start_produce");
  150. int price = rs.getInt("seed_price");
  151. int period = rs.getInt("period");
  152. if (period == PERIOD_CURRENT)
  153. production.add(new SeedProduction(seedId,canProduce,price,startProduce));
  154. else
  155. productionNext.add(new SeedProduction(seedId,canProduce,price,startProduce));
  156. }
  157. statement.close();
  158. rs.close();
  159. castle.setSeedProduction(production, PERIOD_CURRENT);
  160. castle.setSeedProduction(productionNext, PERIOD_NEXT);
  161. // restore procure info
  162. statement = con.prepareStatement(CASTLE_MANOR_LOAD_PROCURE);
  163. statement.setInt(1, castle.getCastleId());
  164. rs = statement.executeQuery();
  165. while(rs.next()) {
  166. int cropId = rs.getInt("crop_id");
  167. int canBuy = rs.getInt("can_buy");
  168. int startBuy = rs.getInt("start_buy");
  169. int rewardType = rs.getInt("reward_type");
  170. int price = rs.getInt("price");
  171. int period = rs.getInt("period");
  172. if (period == PERIOD_CURRENT)
  173. procure.add(new CropProcure(cropId, canBuy, rewardType, startBuy, price));
  174. else
  175. procureNext.add(new CropProcure(cropId, canBuy, rewardType, startBuy, price));
  176. }
  177. statement.close();
  178. rs.close();
  179. castle.setCropProcure(procure, PERIOD_CURRENT);
  180. castle.setCropProcure(procureNext, PERIOD_NEXT);
  181. if (!procure.isEmpty() || !procureNext.isEmpty() ||
  182. !production.isEmpty() || !productionNext.isEmpty())
  183. _log.info(castle.getName() + ": Data loaded");
  184. }
  185. } catch (Exception e) {
  186. _log.info("Error restoring manor data: " + e.getMessage() );
  187. } finally {
  188. try { con.close(); } catch (Exception e) {}
  189. }
  190. }
  191. protected void init() {
  192. _manorRefresh = Calendar.getInstance();
  193. _manorRefresh.set(Calendar.HOUR_OF_DAY, MANOR_REFRESH);
  194. _manorRefresh.set(Calendar.MINUTE, MANOR_REFRESH_MIN);
  195. _periodApprove = Calendar.getInstance();
  196. _periodApprove.set(Calendar.HOUR_OF_DAY, NEXT_PERIOD_APPROVE);
  197. _periodApprove.set(Calendar.MINUTE, NEXT_PERIOD_APPROVE_MIN);
  198. updateManorRefresh();
  199. updatePeriodApprove();
  200. }
  201. public void updateManorRefresh() {
  202. if (Config.DEBUG)
  203. _log.info("Manor System: Manor refresh updated");
  204. _scheduledManorRefresh = ThreadPoolManager.getInstance().scheduleGeneral(new Runnable(){
  205. public void run() {
  206. if (!isDisabled()) {
  207. setUnderMaintenance(true);
  208. _log.info("Manor System: Under maintenance mode started");
  209. _scheduledMaintenanceEnd = ThreadPoolManager.getInstance().scheduleGeneral(new Runnable(){
  210. public void run() {
  211. _log.info("Manor System: Next period started");
  212. setNextPeriod();
  213. try {
  214. save();
  215. } catch (Exception e) {
  216. _log.info("Manor System: Failed to save manor data: " + e);
  217. }
  218. setUnderMaintenance(false);
  219. }
  220. }, MAINTENANCE_PERIOD);
  221. }
  222. updateManorRefresh();
  223. }
  224. }, getMillisToManorRefresh());
  225. }
  226. public void updatePeriodApprove() {
  227. _log.info("Manor System: Manor period approve updated");
  228. _scheduledNextPeriodapprove = ThreadPoolManager.getInstance().scheduleGeneral(new Runnable(){
  229. public void run() {
  230. if (!isDisabled()) {
  231. approveNextPeriod();
  232. _log.info("Manor System: Next period approved");
  233. }
  234. updatePeriodApprove();
  235. }
  236. }, getMillisToNextPeriodApprove());
  237. }
  238. public long getMillisToManorRefresh() {
  239. if (_manorRefresh.getTimeInMillis() > Calendar.getInstance().getTimeInMillis())
  240. return (_manorRefresh.getTimeInMillis() - Calendar.getInstance().getTimeInMillis());
  241. return setNewManorRefresh();
  242. }
  243. public long setNewManorRefresh() {
  244. _manorRefresh = Calendar.getInstance();
  245. _manorRefresh.set(Calendar.HOUR_OF_DAY, MANOR_REFRESH);
  246. _manorRefresh.set(Calendar.MINUTE, MANOR_REFRESH_MIN);
  247. _manorRefresh.add(Calendar.HOUR_OF_DAY, 24);
  248. _log.info("Manor System: New Schedule for manor refresh @ " + _manorRefresh.getTime());
  249. return (_manorRefresh.getTimeInMillis() - Calendar.getInstance().getTimeInMillis());
  250. }
  251. public long getMillisToNextPeriodApprove() {
  252. if (_periodApprove.getTimeInMillis() > Calendar.getInstance().getTimeInMillis())
  253. return (_periodApprove.getTimeInMillis() - Calendar.getInstance().getTimeInMillis());
  254. return setNewPeriodApprove();
  255. }
  256. public long setNewPeriodApprove() {
  257. _periodApprove = Calendar.getInstance();
  258. _periodApprove.set(Calendar.HOUR_OF_DAY, NEXT_PERIOD_APPROVE);
  259. _periodApprove.set(Calendar.MINUTE, NEXT_PERIOD_APPROVE_MIN);
  260. _periodApprove.add(Calendar.HOUR_OF_DAY, 24);
  261. _log.info("Manor System: New Schedule for period approve @ " + _periodApprove.getTime());
  262. return (_periodApprove.getTimeInMillis() - Calendar.getInstance().getTimeInMillis());
  263. }
  264. public void setNextPeriod() {
  265. for (Castle c: CastleManager.getInstance().getCastles()) {
  266. if (c.getOwnerId() <= 0)
  267. continue;
  268. L2Clan clan = ClanTable.getInstance().getClan(c.getOwnerId());
  269. if (clan == null)
  270. continue;
  271. ItemContainer cwh = clan.getWarehouse();
  272. if (!(cwh instanceof ClanWarehouse)) {
  273. _log.info("Can't get clan warehouse for clan " + ClanTable.getInstance().getClan(c.getOwnerId()));
  274. return;
  275. }
  276. for (CropProcure crop: c.getCropProcure(PERIOD_CURRENT)) {
  277. if (crop.getStartAmount() == 0)
  278. continue;
  279. // adding bought crops to clan warehouse
  280. if (crop.getStartAmount() - crop.getAmount() > 0) {
  281. int count = crop.getStartAmount() - crop.getAmount();
  282. count = count * 90 / 100;
  283. if (count < 1) {
  284. if (Rnd.nextInt(99) < 90)
  285. count = 1;
  286. }
  287. if (count > 0) {
  288. cwh.addItem("Manor", L2Manor.getInstance().getMatureCrop(crop.getId()), count, null, null);
  289. }
  290. }
  291. // reserved and not used money giving back to treasury
  292. if (crop.getAmount() > 0) {
  293. c.addToTreasuryNoTax(crop.getAmount() * crop.getPrice());
  294. }
  295. }
  296. c.setSeedProduction(c.getSeedProduction(PERIOD_NEXT), PERIOD_CURRENT);
  297. c.setCropProcure(c.getCropProcure(PERIOD_NEXT), PERIOD_CURRENT);
  298. if (c.getTreasury() < c.getManorCost(PERIOD_CURRENT)) {
  299. c.setSeedProduction(getNewSeedsList(c.getCastleId()), PERIOD_NEXT);
  300. c.setCropProcure(getNewCropsList(c.getCastleId()), PERIOD_NEXT);
  301. } else {
  302. FastList<SeedProduction> production = new FastList<SeedProduction>();
  303. for (SeedProduction s : c.getSeedProduction(PERIOD_CURRENT)) {
  304. s.setCanProduce(s.getStartProduce());
  305. production.add(s);
  306. }
  307. c.setSeedProduction(production, PERIOD_NEXT);
  308. FastList<CropProcure> procure = new FastList<CropProcure>();
  309. for (CropProcure cr : c.getCropProcure(PERIOD_CURRENT)) {
  310. cr.setAmount(cr.getStartAmount());
  311. procure.add(cr);
  312. }
  313. c.setCropProcure(procure, PERIOD_NEXT);
  314. }
  315. if (Config.ALT_MANOR_SAVE_ALL_ACTIONS) {
  316. c.saveCropData();
  317. c.saveSeedData();
  318. }
  319. // Sending notification to a clan leader
  320. L2PcInstance clanLeader = null;
  321. if (clan != null)
  322. clanLeader = L2World.getInstance().getPlayer(clan.getLeader().getName());
  323. if (clanLeader != null)
  324. clanLeader.sendPacket(new SystemMessage(SystemMessageId.THE_MANOR_INFORMATION_HAS_BEEN_UPDATED));
  325. c.setNextPeriodApproved(false);
  326. }
  327. }
  328. public void approveNextPeriod() {
  329. for (Castle c: CastleManager.getInstance().getCastles()) {
  330. boolean notFunc = false;
  331. if (c.getOwnerId() <= 0 ) { // Castle has no owner
  332. c.setCropProcure(new FastList<CropProcure>(), PERIOD_NEXT);
  333. c.setSeedProduction(new FastList<SeedProduction>(), PERIOD_NEXT);
  334. } else if (c.getTreasury() < c.getManorCost(PERIOD_NEXT)) {
  335. notFunc = true;
  336. c.setSeedProduction(getNewSeedsList(c.getCastleId()), PERIOD_NEXT);
  337. c.setCropProcure(getNewCropsList(c.getCastleId()), PERIOD_NEXT);
  338. } else {
  339. ItemContainer cwh = ClanTable.getInstance().getClan(c.getOwnerId()).getWarehouse();
  340. if (!(cwh instanceof ClanWarehouse)) {
  341. _log.info("Can't get clan warehouse for clan " + ClanTable.getInstance().getClan(c.getOwnerId()));
  342. return;
  343. }
  344. int slots = 0;
  345. for (CropProcure crop : c.getCropProcure(PERIOD_NEXT)) {
  346. if (crop.getStartAmount() > 0) {
  347. if (cwh.getItemByItemId(L2Manor.getInstance().getMatureCrop(crop.getId())) == null)
  348. slots++;
  349. }
  350. }
  351. if (!cwh.validateCapacity(slots)) {
  352. notFunc = true;
  353. c.setSeedProduction(getNewSeedsList(c.getCastleId()), PERIOD_NEXT);
  354. c.setCropProcure(getNewCropsList(c.getCastleId()), PERIOD_NEXT);
  355. }
  356. }
  357. c.setNextPeriodApproved(true);
  358. c.addToTreasuryNoTax( (-1)*c.getManorCost(PERIOD_NEXT) );
  359. if (notFunc) {
  360. L2Clan clan = ClanTable.getInstance().getClan(c.getOwnerId());
  361. L2PcInstance clanLeader = null;
  362. if (clan != null)
  363. clanLeader = L2World.getInstance().getPlayer(clan.getLeader().getName());
  364. if (clanLeader != null)
  365. clanLeader.sendPacket(new SystemMessage(SystemMessageId.THE_AMOUNT_IS_NOT_SUFFICIENT_AND_SO_THE_MANOR_IS_NOT_IN_OPERATION));
  366. }
  367. }
  368. }
  369. private FastList<SeedProduction> getNewSeedsList(int castleId) {
  370. FastList<SeedProduction> seeds = new FastList<SeedProduction>();
  371. FastList<Integer> seedsIds = L2Manor.getInstance().getSeedsForCastle(castleId);
  372. for (int sd : seedsIds) {
  373. seeds.add(new SeedProduction(sd));
  374. }
  375. return seeds;
  376. }
  377. private FastList<CropProcure> getNewCropsList(int castleId) {
  378. FastList<CropProcure> crops = new FastList<CropProcure>();
  379. FastList<Integer> cropsIds = L2Manor.getInstance().getCropsForCastle(castleId);
  380. for (int cr : cropsIds) {
  381. crops.add(new CropProcure(cr));
  382. }
  383. return crops;
  384. }
  385. public boolean isUnderMaintenance() {
  386. return _underMaintenance;
  387. }
  388. public void setUnderMaintenance(boolean mode) {
  389. _underMaintenance = mode;
  390. }
  391. public boolean isDisabled() {
  392. return _disabled;
  393. }
  394. public void setDisabled(boolean mode) {
  395. _disabled = mode;
  396. }
  397. public SeedProduction getNewSeedProduction (int id, int amount, int price, int sales) {
  398. return new SeedProduction(id, amount, price, sales);
  399. }
  400. public CropProcure getNewCropProcure (int id, int amount, int type, int price, int buy) {
  401. return new CropProcure(id, amount, type, buy, price);
  402. }
  403. public void save() {
  404. for (Castle c : CastleManager.getInstance().getCastles()) {
  405. c.saveSeedData();
  406. c.saveCropData();
  407. }
  408. }
  409. }