CastleManorManager.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  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 com.l2jserver.gameserver.instancemanager;
  16. import java.sql.Connection;
  17. import java.sql.PreparedStatement;
  18. import java.sql.ResultSet;
  19. import java.util.ArrayList;
  20. import java.util.Calendar;
  21. import java.util.List;
  22. import java.util.concurrent.ScheduledFuture;
  23. import java.util.logging.Level;
  24. import java.util.logging.Logger;
  25. import javolution.util.FastList;
  26. import com.l2jserver.Config;
  27. import com.l2jserver.L2DatabaseFactory;
  28. import com.l2jserver.gameserver.ThreadPoolManager;
  29. import com.l2jserver.gameserver.datatables.ClanTable;
  30. import com.l2jserver.gameserver.datatables.ManorData;
  31. import com.l2jserver.gameserver.model.L2Clan;
  32. import com.l2jserver.gameserver.model.L2World;
  33. import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
  34. import com.l2jserver.gameserver.model.entity.Castle;
  35. import com.l2jserver.gameserver.model.itemcontainer.ClanWarehouse;
  36. import com.l2jserver.gameserver.model.itemcontainer.ItemContainer;
  37. import com.l2jserver.gameserver.network.SystemMessageId;
  38. import com.l2jserver.util.Rnd;
  39. /**
  40. * Class For Castle Manor Manager Load manor data from DB Update/Reload/Delete Handles all schedule for manor
  41. * @author l3x
  42. */
  43. public class CastleManorManager
  44. {
  45. protected static final Logger _log = Logger.getLogger(CastleManorManager.class.getName());
  46. public static final int PERIOD_CURRENT = 0;
  47. public static final int PERIOD_NEXT = 1;
  48. private static final String CASTLE_MANOR_LOAD_PROCURE = "SELECT * FROM castle_manor_procure WHERE castle_id=?";
  49. private static final String CASTLE_MANOR_LOAD_PRODUCTION = "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. {
  64. return SingletonHolder._instance;
  65. }
  66. public static class CropProcure
  67. {
  68. final int _cropId;
  69. long _buyResidual;
  70. final int _rewardType;
  71. final long _buy;
  72. final long _price;
  73. public CropProcure(int id)
  74. {
  75. _cropId = id;
  76. _buyResidual = 0;
  77. _rewardType = 0;
  78. _buy = 0;
  79. _price = 0;
  80. }
  81. public CropProcure(int id, long amount, int type, long buy, long price)
  82. {
  83. _cropId = id;
  84. _buyResidual = amount;
  85. _rewardType = type;
  86. _buy = buy;
  87. _price = price;
  88. }
  89. public int getReward()
  90. {
  91. return _rewardType;
  92. }
  93. public int getId()
  94. {
  95. return _cropId;
  96. }
  97. public long getAmount()
  98. {
  99. return _buyResidual;
  100. }
  101. public long getStartAmount()
  102. {
  103. return _buy;
  104. }
  105. public long getPrice()
  106. {
  107. return _price;
  108. }
  109. public void setAmount(long amount)
  110. {
  111. _buyResidual = amount;
  112. }
  113. }
  114. public static class SeedProduction
  115. {
  116. final int _seedId;
  117. long _residual;
  118. final long _price;
  119. final long _sales;
  120. public SeedProduction(int id)
  121. {
  122. _seedId = id;
  123. _residual = 0;
  124. _price = 0;
  125. _sales = 0;
  126. }
  127. public SeedProduction(int id, long amount, long price, long sales)
  128. {
  129. _seedId = id;
  130. _residual = amount;
  131. _price = price;
  132. _sales = sales;
  133. }
  134. public int getId()
  135. {
  136. return _seedId;
  137. }
  138. public long getCanProduce()
  139. {
  140. return _residual;
  141. }
  142. public long getPrice()
  143. {
  144. return _price;
  145. }
  146. public long getStartProduce()
  147. {
  148. return _sales;
  149. }
  150. public void setCanProduce(long amount)
  151. {
  152. _residual = amount;
  153. }
  154. }
  155. protected CastleManorManager()
  156. {
  157. load(); // load data from database
  158. init(); // schedule all manor related events
  159. _underMaintenance = false;
  160. _disabled = !Config.ALLOW_MANOR;
  161. boolean isApproved;
  162. if (_periodApprove.getTimeInMillis() > _manorRefresh.getTimeInMillis())
  163. {
  164. // Next approve period already scheduled
  165. isApproved = (_manorRefresh.getTimeInMillis() > Calendar.getInstance().getTimeInMillis());
  166. }
  167. else
  168. {
  169. isApproved = ((_periodApprove.getTimeInMillis() < Calendar.getInstance().getTimeInMillis()) && (_manorRefresh.getTimeInMillis() > Calendar.getInstance().getTimeInMillis()));
  170. }
  171. for (Castle c : CastleManager.getInstance().getCastles())
  172. {
  173. c.setNextPeriodApproved(isApproved);
  174. }
  175. }
  176. private void load()
  177. {
  178. try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  179. {
  180. PreparedStatement statementProduction = con.prepareStatement(CASTLE_MANOR_LOAD_PRODUCTION);
  181. PreparedStatement statementProcure = con.prepareStatement(CASTLE_MANOR_LOAD_PROCURE);
  182. for (Castle castle : CastleManager.getInstance().getCastles())
  183. {
  184. FastList<SeedProduction> production = new FastList<>();
  185. FastList<SeedProduction> productionNext = new FastList<>();
  186. FastList<CropProcure> procure = new FastList<>();
  187. FastList<CropProcure> procureNext = new FastList<>();
  188. // restore seed production info
  189. statementProduction.setInt(1, castle.getCastleId());
  190. ResultSet rs = statementProduction.executeQuery();
  191. statementProduction.clearParameters();
  192. while (rs.next())
  193. {
  194. int seedId = rs.getInt("seed_id");
  195. int canProduce = rs.getInt("can_produce");
  196. int startProduce = rs.getInt("start_produce");
  197. int price = rs.getInt("seed_price");
  198. int period = rs.getInt("period");
  199. if (period == PERIOD_CURRENT)
  200. {
  201. production.add(new SeedProduction(seedId, canProduce, price, startProduce));
  202. }
  203. else
  204. {
  205. productionNext.add(new SeedProduction(seedId, canProduce, price, startProduce));
  206. }
  207. }
  208. rs.close();
  209. castle.setSeedProduction(production, PERIOD_CURRENT);
  210. castle.setSeedProduction(productionNext, PERIOD_NEXT);
  211. // restore procure info
  212. statementProcure.setInt(1, castle.getCastleId());
  213. rs = statementProcure.executeQuery();
  214. statementProcure.clearParameters();
  215. while (rs.next())
  216. {
  217. int cropId = rs.getInt("crop_id");
  218. int canBuy = rs.getInt("can_buy");
  219. int startBuy = rs.getInt("start_buy");
  220. int rewardType = rs.getInt("reward_type");
  221. int price = rs.getInt("price");
  222. int period = rs.getInt("period");
  223. if (period == PERIOD_CURRENT)
  224. {
  225. procure.add(new CropProcure(cropId, canBuy, rewardType, startBuy, price));
  226. }
  227. else
  228. {
  229. procureNext.add(new CropProcure(cropId, canBuy, rewardType, startBuy, price));
  230. }
  231. }
  232. rs.close();
  233. castle.setCropProcure(procure, PERIOD_CURRENT);
  234. castle.setCropProcure(procureNext, PERIOD_NEXT);
  235. if (!procure.isEmpty() || !procureNext.isEmpty() || !production.isEmpty() || !productionNext.isEmpty())
  236. {
  237. _log.info(getClass().getSimpleName() + ": " + castle.getName() + ": Data loaded");
  238. }
  239. }
  240. statementProduction.close();
  241. statementProcure.close();
  242. }
  243. catch (Exception e)
  244. {
  245. _log.info("Error restoring manor data: " + e.getMessage());
  246. }
  247. }
  248. private void init()
  249. {
  250. _manorRefresh = Calendar.getInstance();
  251. _manorRefresh.set(Calendar.HOUR_OF_DAY, MANOR_REFRESH);
  252. _manorRefresh.set(Calendar.MINUTE, MANOR_REFRESH_MIN);
  253. _periodApprove = Calendar.getInstance();
  254. _periodApprove.set(Calendar.HOUR_OF_DAY, NEXT_PERIOD_APPROVE);
  255. _periodApprove.set(Calendar.MINUTE, NEXT_PERIOD_APPROVE_MIN);
  256. updateManorRefresh();
  257. updatePeriodApprove();
  258. }
  259. public void updateManorRefresh()
  260. {
  261. _log.info("Manor System: Manor refresh updated");
  262. _scheduledManorRefresh = ThreadPoolManager.getInstance().scheduleGeneral(new Runnable()
  263. {
  264. @Override
  265. public void run()
  266. {
  267. if (!isDisabled())
  268. {
  269. setUnderMaintenance(true);
  270. _log.info("Manor System: Under maintenance mode started");
  271. _scheduledMaintenanceEnd = ThreadPoolManager.getInstance().scheduleGeneral(new Runnable()
  272. {
  273. @Override
  274. public void run()
  275. {
  276. _log.info("Manor System: Next period started");
  277. setNextPeriod();
  278. try
  279. {
  280. save();
  281. }
  282. catch (Exception e)
  283. {
  284. _log.log(Level.WARNING, "Manor System: Failed to save manor data: " + e.getMessage(), e);
  285. }
  286. setUnderMaintenance(false);
  287. }
  288. }, MAINTENANCE_PERIOD);
  289. }
  290. updateManorRefresh();
  291. }
  292. }, getMillisToManorRefresh());
  293. }
  294. public void updatePeriodApprove()
  295. {
  296. _log.info("Manor System: Manor period approve updated");
  297. _scheduledNextPeriodapprove = ThreadPoolManager.getInstance().scheduleGeneral(new Runnable()
  298. {
  299. @Override
  300. public void run()
  301. {
  302. if (!isDisabled())
  303. {
  304. approveNextPeriod();
  305. _log.info("Manor System: Next period approved");
  306. }
  307. updatePeriodApprove();
  308. }
  309. }, getMillisToNextPeriodApprove());
  310. }
  311. public long getMillisToManorRefresh()
  312. {
  313. // use safe interval 120s to prevent double run
  314. if ((_manorRefresh.getTimeInMillis() - Calendar.getInstance().getTimeInMillis()) < 120000)
  315. {
  316. setNewManorRefresh();
  317. }
  318. _log.info("Manor System: New Schedule for manor refresh @ " + _manorRefresh.getTime());
  319. return (_manorRefresh.getTimeInMillis() - Calendar.getInstance().getTimeInMillis());
  320. }
  321. public void setNewManorRefresh()
  322. {
  323. _manorRefresh = Calendar.getInstance();
  324. _manorRefresh.set(Calendar.HOUR_OF_DAY, MANOR_REFRESH);
  325. _manorRefresh.set(Calendar.MINUTE, MANOR_REFRESH_MIN);
  326. _manorRefresh.set(Calendar.SECOND, 0);
  327. _manorRefresh.add(Calendar.HOUR_OF_DAY, 24);
  328. }
  329. public long getMillisToNextPeriodApprove()
  330. {
  331. // use safe interval 120s to prevent double run
  332. if ((_periodApprove.getTimeInMillis() - Calendar.getInstance().getTimeInMillis()) < 120000)
  333. {
  334. setNewPeriodApprove();
  335. }
  336. _log.info("Manor System: New Schedule for period approve @ " + _periodApprove.getTime());
  337. return (_periodApprove.getTimeInMillis() - Calendar.getInstance().getTimeInMillis());
  338. }
  339. public void setNewPeriodApprove()
  340. {
  341. _periodApprove = Calendar.getInstance();
  342. _periodApprove.set(Calendar.HOUR_OF_DAY, NEXT_PERIOD_APPROVE);
  343. _periodApprove.set(Calendar.MINUTE, NEXT_PERIOD_APPROVE_MIN);
  344. _periodApprove.set(Calendar.SECOND, 0);
  345. _periodApprove.add(Calendar.HOUR_OF_DAY, 24);
  346. }
  347. public void setNextPeriod()
  348. {
  349. for (Castle c : CastleManager.getInstance().getCastles())
  350. {
  351. if (c.getOwnerId() <= 0)
  352. {
  353. continue;
  354. }
  355. L2Clan clan = ClanTable.getInstance().getClan(c.getOwnerId());
  356. if (clan == null)
  357. {
  358. continue;
  359. }
  360. ItemContainer cwh = clan.getWarehouse();
  361. if (!(cwh instanceof ClanWarehouse))
  362. {
  363. _log.info("Can't get clan warehouse for clan " + ClanTable.getInstance().getClan(c.getOwnerId()));
  364. continue;
  365. }
  366. for (CropProcure crop : c.getCropProcure(PERIOD_CURRENT))
  367. {
  368. if (crop.getStartAmount() == 0)
  369. {
  370. continue;
  371. }
  372. // adding bought crops to clan warehouse
  373. if ((crop.getStartAmount() - crop.getAmount()) > 0)
  374. {
  375. long count = crop.getStartAmount() - crop.getAmount();
  376. count = (count * 90) / 100;
  377. if (count < 1)
  378. {
  379. if (Rnd.nextInt(99) < 90)
  380. {
  381. count = 1;
  382. }
  383. }
  384. if (count > 0)
  385. {
  386. cwh.addItem("Manor", ManorData.getInstance().getMatureCrop(crop.getId()), count, null, null);
  387. }
  388. }
  389. // reserved and not used money giving back to treasury
  390. if (crop.getAmount() > 0)
  391. {
  392. c.addToTreasuryNoTax(crop.getAmount() * crop.getPrice());
  393. }
  394. }
  395. c.setSeedProduction(c.getSeedProduction(PERIOD_NEXT), PERIOD_CURRENT);
  396. c.setCropProcure(c.getCropProcure(PERIOD_NEXT), PERIOD_CURRENT);
  397. if (c.getTreasury() < c.getManorCost(PERIOD_CURRENT))
  398. {
  399. c.setSeedProduction(getNewSeedsList(c.getCastleId()), PERIOD_NEXT);
  400. c.setCropProcure(getNewCropsList(c.getCastleId()), PERIOD_NEXT);
  401. }
  402. else
  403. {
  404. FastList<SeedProduction> production = new FastList<>();
  405. for (SeedProduction s : c.getSeedProduction(PERIOD_CURRENT))
  406. {
  407. s.setCanProduce(s.getStartProduce());
  408. production.add(s);
  409. }
  410. c.setSeedProduction(production, PERIOD_NEXT);
  411. FastList<CropProcure> procure = new FastList<>();
  412. for (CropProcure cr : c.getCropProcure(PERIOD_CURRENT))
  413. {
  414. cr.setAmount(cr.getStartAmount());
  415. procure.add(cr);
  416. }
  417. c.setCropProcure(procure, PERIOD_NEXT);
  418. }
  419. if (Config.ALT_MANOR_SAVE_ALL_ACTIONS)
  420. {
  421. c.saveCropData();
  422. c.saveSeedData();
  423. }
  424. // Sending notification to a clan leader
  425. L2PcInstance clanLeader = null;
  426. clanLeader = L2World.getInstance().getPlayer(clan.getLeader().getName());
  427. if (clanLeader != null)
  428. {
  429. clanLeader.sendPacket(SystemMessageId.THE_MANOR_INFORMATION_HAS_BEEN_UPDATED);
  430. }
  431. c.setNextPeriodApproved(false);
  432. }
  433. }
  434. public void approveNextPeriod()
  435. {
  436. for (Castle c : CastleManager.getInstance().getCastles())
  437. {
  438. boolean notFunc = false;
  439. if (c.getOwnerId() <= 0)
  440. { // Castle has no owner
  441. c.setCropProcure(new FastList<CropProcure>(), PERIOD_NEXT);
  442. c.setSeedProduction(new FastList<SeedProduction>(), PERIOD_NEXT);
  443. }
  444. else if (c.getTreasury() < c.getManorCost(PERIOD_NEXT))
  445. {
  446. notFunc = true;
  447. _log.info("Manor for castle " + c.getName() + " disabled, not enough adena in treasury: " + c.getTreasury() + ", " + c.getManorCost(PERIOD_NEXT) + " required.");
  448. c.setSeedProduction(getNewSeedsList(c.getCastleId()), PERIOD_NEXT);
  449. c.setCropProcure(getNewCropsList(c.getCastleId()), PERIOD_NEXT);
  450. }
  451. else
  452. {
  453. ItemContainer cwh = ClanTable.getInstance().getClan(c.getOwnerId()).getWarehouse();
  454. if (!(cwh instanceof ClanWarehouse))
  455. {
  456. _log.info("Can't get clan warehouse for clan " + ClanTable.getInstance().getClan(c.getOwnerId()));
  457. continue;
  458. }
  459. int slots = 0;
  460. for (CropProcure crop : c.getCropProcure(PERIOD_NEXT))
  461. {
  462. if (crop.getStartAmount() > 0)
  463. {
  464. if (cwh.getItemByItemId(ManorData.getInstance().getMatureCrop(crop.getId())) == null)
  465. {
  466. slots++;
  467. }
  468. }
  469. }
  470. if (!cwh.validateCapacity(slots))
  471. {
  472. notFunc = true;
  473. _log.info("Manor for castle " + c.getName() + " disabled, not enough free slots in clan warehouse: " + (Config.WAREHOUSE_SLOTS_CLAN - cwh.getSize()) + ", but " + slots + " required.");
  474. c.setSeedProduction(getNewSeedsList(c.getCastleId()), PERIOD_NEXT);
  475. c.setCropProcure(getNewCropsList(c.getCastleId()), PERIOD_NEXT);
  476. }
  477. }
  478. c.setNextPeriodApproved(true);
  479. c.addToTreasuryNoTax((-1) * c.getManorCost(PERIOD_NEXT));
  480. if (notFunc)
  481. {
  482. L2Clan clan = ClanTable.getInstance().getClan(c.getOwnerId());
  483. L2PcInstance clanLeader = null;
  484. if (clan != null)
  485. {
  486. clanLeader = L2World.getInstance().getPlayer(clan.getLeaderId());
  487. }
  488. if (clanLeader != null)
  489. {
  490. clanLeader.sendPacket(SystemMessageId.THE_AMOUNT_IS_NOT_SUFFICIENT_AND_SO_THE_MANOR_IS_NOT_IN_OPERATION);
  491. }
  492. }
  493. }
  494. }
  495. private List<SeedProduction> getNewSeedsList(int castleId)
  496. {
  497. List<SeedProduction> seeds = new ArrayList<>();
  498. List<Integer> seedsIds = ManorData.getInstance().getSeedsForCastle(castleId);
  499. for (int sd : seedsIds)
  500. {
  501. seeds.add(new SeedProduction(sd));
  502. }
  503. return seeds;
  504. }
  505. private List<CropProcure> getNewCropsList(int castleId)
  506. {
  507. List<CropProcure> crops = new ArrayList<>();
  508. List<Integer> cropsIds = ManorData.getInstance().getCropsForCastle(castleId);
  509. for (int cr : cropsIds)
  510. {
  511. crops.add(new CropProcure(cr));
  512. }
  513. return crops;
  514. }
  515. public boolean isUnderMaintenance()
  516. {
  517. return _underMaintenance;
  518. }
  519. public void setUnderMaintenance(boolean mode)
  520. {
  521. _underMaintenance = mode;
  522. }
  523. public boolean isDisabled()
  524. {
  525. return _disabled;
  526. }
  527. public void setDisabled(boolean mode)
  528. {
  529. _disabled = mode;
  530. }
  531. public SeedProduction getNewSeedProduction(int id, long amount, long price, long sales)
  532. {
  533. return new SeedProduction(id, amount, price, sales);
  534. }
  535. public CropProcure getNewCropProcure(int id, long amount, int type, long price, long buy)
  536. {
  537. return new CropProcure(id, amount, type, buy, price);
  538. }
  539. public void save()
  540. {
  541. for (Castle c : CastleManager.getInstance().getCastles())
  542. {
  543. c.saveSeedData();
  544. c.saveCropData();
  545. }
  546. }
  547. private static class SingletonHolder
  548. {
  549. protected static final CastleManorManager _instance = new CastleManorManager();
  550. }
  551. }