CastleManorManager.java 17 KB

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