CastleManorManager.java 17 KB

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