Castle.java 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602
  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.model.entity;
  16. import java.sql.Connection;
  17. import java.sql.PreparedStatement;
  18. import java.sql.ResultSet;
  19. import java.sql.Statement;
  20. import java.util.ArrayList;
  21. import java.util.Calendar;
  22. import java.util.List;
  23. import java.util.Map;
  24. import java.util.logging.Level;
  25. import java.util.logging.Logger;
  26. import javolution.util.FastMap;
  27. import com.l2jserver.Config;
  28. import com.l2jserver.L2DatabaseFactory;
  29. import com.l2jserver.gameserver.CastleUpdater;
  30. import com.l2jserver.gameserver.SevenSigns;
  31. import com.l2jserver.gameserver.ThreadPoolManager;
  32. import com.l2jserver.gameserver.datatables.ClanTable;
  33. import com.l2jserver.gameserver.datatables.DoorTable;
  34. import com.l2jserver.gameserver.datatables.ManorData;
  35. import com.l2jserver.gameserver.datatables.SkillTable;
  36. import com.l2jserver.gameserver.datatables.SkillTreesData;
  37. import com.l2jserver.gameserver.instancemanager.CastleManager;
  38. import com.l2jserver.gameserver.instancemanager.CastleManorManager;
  39. import com.l2jserver.gameserver.instancemanager.CastleManorManager.CropProcure;
  40. import com.l2jserver.gameserver.instancemanager.CastleManorManager.SeedProduction;
  41. import com.l2jserver.gameserver.instancemanager.FortManager;
  42. import com.l2jserver.gameserver.instancemanager.TerritoryWarManager;
  43. import com.l2jserver.gameserver.instancemanager.TerritoryWarManager.Territory;
  44. import com.l2jserver.gameserver.instancemanager.ZoneManager;
  45. import com.l2jserver.gameserver.model.L2Clan;
  46. import com.l2jserver.gameserver.model.L2Object;
  47. import com.l2jserver.gameserver.model.L2SkillLearn;
  48. import com.l2jserver.gameserver.model.actor.instance.L2ArtefactInstance;
  49. import com.l2jserver.gameserver.model.actor.instance.L2DoorInstance;
  50. import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
  51. import com.l2jserver.gameserver.model.itemcontainer.PcInventory;
  52. import com.l2jserver.gameserver.model.skills.L2Skill;
  53. import com.l2jserver.gameserver.model.zone.type.L2CastleZone;
  54. import com.l2jserver.gameserver.model.zone.type.L2ResidenceTeleportZone;
  55. import com.l2jserver.gameserver.model.zone.type.L2SiegeZone;
  56. import com.l2jserver.gameserver.network.serverpackets.PlaySound;
  57. import com.l2jserver.gameserver.network.serverpackets.PledgeShowInfoUpdate;
  58. import gnu.trove.map.hash.TIntIntHashMap;
  59. public class Castle
  60. {
  61. protected static final Logger _log = Logger.getLogger(Castle.class.getName());
  62. private static final String CASTLE_MANOR_DELETE_PRODUCTION = "DELETE FROM castle_manor_production WHERE castle_id=?;";
  63. private static final String CASTLE_MANOR_DELETE_PRODUCTION_PERIOD = "DELETE FROM castle_manor_production WHERE castle_id=? AND period=?;";
  64. private static final String CASTLE_MANOR_DELETE_PROCURE = "DELETE FROM castle_manor_procure WHERE castle_id=?;";
  65. private static final String CASTLE_MANOR_DELETE_PROCURE_PERIOD = "DELETE FROM castle_manor_procure WHERE castle_id=? AND period=?;";
  66. private static final String CASTLE_UPDATE_CROP = "UPDATE castle_manor_procure SET can_buy=? WHERE crop_id=? AND castle_id=? AND period=?";
  67. private static final String CASTLE_UPDATE_SEED = "UPDATE castle_manor_production SET can_produce=? WHERE seed_id=? AND castle_id=? AND period=?";
  68. private int _castleId = 0;
  69. private final List<L2DoorInstance> _doors = new ArrayList<>();
  70. private String _name = "";
  71. private int _ownerId = 0;
  72. private Siege _siege = null;
  73. private Calendar _siegeDate;
  74. private boolean _isTimeRegistrationOver = true; // true if Castle Lords set the time, or 24h is elapsed after the siege
  75. private Calendar _siegeTimeRegistrationEndDate; // last siege end date + 1 day
  76. private int _taxPercent = 0;
  77. private double _taxRate = 0;
  78. private long _treasury = 0;
  79. private boolean _showNpcCrest = false;
  80. private L2SiegeZone _zone = null;
  81. private L2CastleZone _castleZone = null;
  82. private L2ResidenceTeleportZone _teleZone;
  83. private L2Clan _formerOwner = null;
  84. private final List<L2ArtefactInstance> _artefacts = new ArrayList<>(1);
  85. private final TIntIntHashMap _engrave = new TIntIntHashMap(1);
  86. private final Map<Integer, CastleFunction> _function;
  87. private final List<L2Skill> _residentialSkills = new ArrayList<>();
  88. private int _ticketBuyCount = 0;
  89. private List<CropProcure> _procure = new ArrayList<>();
  90. private List<SeedProduction> _production = new ArrayList<>();
  91. private List<CropProcure> _procureNext = new ArrayList<>();
  92. private List<SeedProduction> _productionNext = new ArrayList<>();
  93. private boolean _isNextPeriodApproved = false;
  94. /** Castle Functions */
  95. public static final int FUNC_TELEPORT = 1;
  96. public static final int FUNC_RESTORE_HP = 2;
  97. public static final int FUNC_RESTORE_MP = 3;
  98. public static final int FUNC_RESTORE_EXP = 4;
  99. public static final int FUNC_SUPPORT = 5;
  100. public class CastleFunction
  101. {
  102. private final int _type;
  103. private int _lvl;
  104. protected int _fee;
  105. protected int _tempFee;
  106. private final long _rate;
  107. private long _endDate;
  108. protected boolean _inDebt;
  109. public boolean _cwh;
  110. public CastleFunction(int type, int lvl, int lease, int tempLease, long rate, long time, boolean cwh)
  111. {
  112. _type = type;
  113. _lvl = lvl;
  114. _fee = lease;
  115. _tempFee = tempLease;
  116. _rate = rate;
  117. _endDate = time;
  118. initializeTask(cwh);
  119. }
  120. public int getType()
  121. {
  122. return _type;
  123. }
  124. public int getLvl()
  125. {
  126. return _lvl;
  127. }
  128. public int getLease()
  129. {
  130. return _fee;
  131. }
  132. public long getRate()
  133. {
  134. return _rate;
  135. }
  136. public long getEndTime()
  137. {
  138. return _endDate;
  139. }
  140. public void setLvl(int lvl)
  141. {
  142. _lvl = lvl;
  143. }
  144. public void setLease(int lease)
  145. {
  146. _fee = lease;
  147. }
  148. public void setEndTime(long time)
  149. {
  150. _endDate = time;
  151. }
  152. private void initializeTask(boolean cwh)
  153. {
  154. if (getOwnerId() <= 0)
  155. {
  156. return;
  157. }
  158. long currentTime = System.currentTimeMillis();
  159. if (_endDate > currentTime)
  160. {
  161. ThreadPoolManager.getInstance().scheduleGeneral(new FunctionTask(cwh), _endDate - currentTime);
  162. }
  163. else
  164. {
  165. ThreadPoolManager.getInstance().scheduleGeneral(new FunctionTask(cwh), 0);
  166. }
  167. }
  168. private class FunctionTask implements Runnable
  169. {
  170. public FunctionTask(boolean cwh)
  171. {
  172. _cwh = cwh;
  173. }
  174. @Override
  175. public void run()
  176. {
  177. try
  178. {
  179. if (getOwnerId() <= 0)
  180. {
  181. return;
  182. }
  183. if ((ClanTable.getInstance().getClan(getOwnerId()).getWarehouse().getAdena() >= _fee) || !_cwh)
  184. {
  185. int fee = _fee;
  186. if (getEndTime() == -1)
  187. {
  188. fee = _tempFee;
  189. }
  190. setEndTime(System.currentTimeMillis() + getRate());
  191. dbSave();
  192. if (_cwh)
  193. {
  194. ClanTable.getInstance().getClan(getOwnerId()).getWarehouse().destroyItemByItemId("CS_function_fee", PcInventory.ADENA_ID, fee, null, null);
  195. }
  196. ThreadPoolManager.getInstance().scheduleGeneral(new FunctionTask(true), getRate());
  197. }
  198. else
  199. {
  200. removeFunction(getType());
  201. }
  202. }
  203. catch (Exception e)
  204. {
  205. _log.log(Level.SEVERE, "", e);
  206. }
  207. }
  208. }
  209. public void dbSave()
  210. {
  211. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  212. PreparedStatement ps = con.prepareStatement("REPLACE INTO castle_functions (castle_id, type, lvl, lease, rate, endTime) VALUES (?,?,?,?,?,?)"))
  213. {
  214. ps.setInt(1, getCastleId());
  215. ps.setInt(2, getType());
  216. ps.setInt(3, getLvl());
  217. ps.setInt(4, getLease());
  218. ps.setLong(5, getRate());
  219. ps.setLong(6, getEndTime());
  220. ps.execute();
  221. }
  222. catch (Exception e)
  223. {
  224. _log.log(Level.SEVERE, "Exception: Castle.updateFunctions(int type, int lvl, int lease, long rate, long time, boolean addNew): " + e.getMessage(), e);
  225. }
  226. }
  227. }
  228. public Castle(int castleId)
  229. {
  230. _castleId = castleId;
  231. /*
  232. * if (_castleId == 7 || castleId == 9) // Goddard and Schuttgart _nbArtifact = 2;
  233. */
  234. load();
  235. _function = new FastMap<>();
  236. final List<L2SkillLearn> residentialSkills = SkillTreesData.getInstance().getAvailableResidentialSkills(castleId);
  237. for (L2SkillLearn s : residentialSkills)
  238. {
  239. final L2Skill sk = SkillTable.getInstance().getInfo(s.getSkillId(), s.getSkillLevel());
  240. if (sk != null)
  241. {
  242. _residentialSkills.add(sk);
  243. }
  244. else
  245. {
  246. _log.warning("Castle Id: " + castleId + " has a null residential skill Id: " + s.getSkillId() + " level: " + s.getSkillLevel() + "!");
  247. }
  248. }
  249. if (getOwnerId() != 0)
  250. {
  251. loadFunctions();
  252. }
  253. }
  254. /**
  255. * Return function with id
  256. * @param type
  257. * @return
  258. */
  259. public CastleFunction getFunction(int type)
  260. {
  261. if (_function.containsKey(type))
  262. {
  263. return _function.get(type);
  264. }
  265. return null;
  266. }
  267. public synchronized void engrave(L2Clan clan, L2Object target)
  268. {
  269. if (!_artefacts.contains(target))
  270. {
  271. return;
  272. }
  273. _engrave.put(target.getObjectId(), clan.getClanId());
  274. if (_engrave.size() == _artefacts.size())
  275. {
  276. for (L2ArtefactInstance art : _artefacts)
  277. {
  278. if (_engrave.get(art.getObjectId()) != clan.getClanId())
  279. {
  280. return;
  281. }
  282. }
  283. _engrave.clear();
  284. setOwner(clan);
  285. }
  286. }
  287. // This method add to the treasury
  288. /**
  289. * Add amount to castle instance's treasury (warehouse).
  290. * @param amount
  291. */
  292. public void addToTreasury(long amount)
  293. {
  294. // check if owned
  295. if (getOwnerId() <= 0)
  296. {
  297. return;
  298. }
  299. if (_name.equalsIgnoreCase("Schuttgart") || _name.equalsIgnoreCase("Goddard"))
  300. {
  301. Castle rune = CastleManager.getInstance().getCastle("rune");
  302. if (rune != null)
  303. {
  304. long runeTax = (long) (amount * rune.getTaxRate());
  305. if (rune.getOwnerId() > 0)
  306. {
  307. rune.addToTreasury(runeTax);
  308. }
  309. amount -= runeTax;
  310. }
  311. }
  312. if (!_name.equalsIgnoreCase("aden") && !_name.equalsIgnoreCase("Rune") && !_name.equalsIgnoreCase("Schuttgart") && !_name.equalsIgnoreCase("Goddard")) // If current castle instance is not Aden, Rune, Goddard or Schuttgart.
  313. {
  314. Castle aden = CastleManager.getInstance().getCastle("aden");
  315. if (aden != null)
  316. {
  317. long adenTax = (long) (amount * aden.getTaxRate()); // Find out what Aden gets from the current castle instance's income
  318. if (aden.getOwnerId() > 0)
  319. {
  320. aden.addToTreasury(adenTax); // Only bother to really add the tax to the treasury if not npc owned
  321. }
  322. amount -= adenTax; // Subtract Aden's income from current castle instance's income
  323. }
  324. }
  325. addToTreasuryNoTax(amount);
  326. }
  327. /**
  328. * Add amount to castle instance's treasury (warehouse), no tax paying.
  329. * @param amount
  330. * @return
  331. */
  332. public boolean addToTreasuryNoTax(long amount)
  333. {
  334. if (getOwnerId() <= 0)
  335. {
  336. return false;
  337. }
  338. if (amount < 0)
  339. {
  340. amount *= -1;
  341. if (_treasury < amount)
  342. {
  343. return false;
  344. }
  345. _treasury -= amount;
  346. }
  347. else
  348. {
  349. if ((_treasury + amount) > PcInventory.MAX_ADENA)
  350. {
  351. _treasury = PcInventory.MAX_ADENA;
  352. }
  353. else
  354. {
  355. _treasury += amount;
  356. }
  357. }
  358. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  359. PreparedStatement ps = con.prepareStatement("UPDATE castle SET treasury = ? WHERE id = ?"))
  360. {
  361. ps.setLong(1, getTreasury());
  362. ps.setInt(2, getCastleId());
  363. ps.execute();
  364. }
  365. catch (Exception e)
  366. {
  367. _log.log(Level.WARNING, e.getMessage(), e);
  368. }
  369. return true;
  370. }
  371. /**
  372. * Move non clan members off castle area and to nearest town.
  373. */
  374. public void banishForeigners()
  375. {
  376. getCastleZone().banishForeigners(getOwnerId());
  377. }
  378. /**
  379. * Return true if object is inside the zone
  380. * @param x
  381. * @param y
  382. * @param z
  383. * @return
  384. */
  385. public boolean checkIfInZone(int x, int y, int z)
  386. {
  387. return getZone().isInsideZone(x, y, z);
  388. }
  389. public L2SiegeZone getZone()
  390. {
  391. if (_zone == null)
  392. {
  393. for (L2SiegeZone zone : ZoneManager.getInstance().getAllZones(L2SiegeZone.class))
  394. {
  395. if (zone.getSiegeObjectId() == getCastleId())
  396. {
  397. _zone = zone;
  398. break;
  399. }
  400. }
  401. }
  402. return _zone;
  403. }
  404. public L2CastleZone getCastleZone()
  405. {
  406. if (_castleZone == null)
  407. {
  408. for (L2CastleZone zone : ZoneManager.getInstance().getAllZones(L2CastleZone.class))
  409. {
  410. if (zone.getCastleId() == getCastleId())
  411. {
  412. _castleZone = zone;
  413. break;
  414. }
  415. }
  416. }
  417. return _castleZone;
  418. }
  419. public L2ResidenceTeleportZone getTeleZone()
  420. {
  421. if (_teleZone == null)
  422. {
  423. for (L2ResidenceTeleportZone zone : ZoneManager.getInstance().getAllZones(L2ResidenceTeleportZone.class))
  424. {
  425. if (zone.getResidenceId() == getCastleId())
  426. {
  427. _teleZone = zone;
  428. break;
  429. }
  430. }
  431. }
  432. return _teleZone;
  433. }
  434. public void oustAllPlayers()
  435. {
  436. getTeleZone().oustAllPlayers();
  437. }
  438. /**
  439. * Get the objects distance to this castle
  440. * @param obj
  441. * @return
  442. */
  443. public double getDistance(L2Object obj)
  444. {
  445. return getZone().getDistanceToZone(obj);
  446. }
  447. public void closeDoor(L2PcInstance activeChar, int doorId)
  448. {
  449. openCloseDoor(activeChar, doorId, false);
  450. }
  451. public void openDoor(L2PcInstance activeChar, int doorId)
  452. {
  453. openCloseDoor(activeChar, doorId, true);
  454. }
  455. public void openCloseDoor(L2PcInstance activeChar, int doorId, boolean open)
  456. {
  457. if (activeChar.getClanId() != getOwnerId())
  458. {
  459. return;
  460. }
  461. L2DoorInstance door = getDoor(doorId);
  462. if (door != null)
  463. {
  464. if (open)
  465. {
  466. door.openMe();
  467. }
  468. else
  469. {
  470. door.closeMe();
  471. }
  472. }
  473. }
  474. // This method is used to begin removing all castle upgrades
  475. public void removeUpgrade()
  476. {
  477. removeDoorUpgrade();
  478. for (Integer fc : _function.keySet())
  479. {
  480. removeFunction(fc);
  481. }
  482. _function.clear();
  483. }
  484. // This method updates the castle tax rate
  485. public void setOwner(L2Clan clan)
  486. {
  487. // Remove old owner
  488. if ((getOwnerId() > 0) && ((clan == null) || (clan.getClanId() != getOwnerId())))
  489. {
  490. L2Clan oldOwner = ClanTable.getInstance().getClan(getOwnerId()); // Try to find clan instance
  491. if (oldOwner != null)
  492. {
  493. if (_formerOwner == null)
  494. {
  495. _formerOwner = oldOwner;
  496. if (Config.REMOVE_CASTLE_CIRCLETS)
  497. {
  498. CastleManager.getInstance().removeCirclet(_formerOwner, getCastleId());
  499. }
  500. }
  501. try
  502. {
  503. L2PcInstance oldleader = oldOwner.getLeader().getPlayerInstance();
  504. if (oldleader != null)
  505. {
  506. if (oldleader.getMountType() == 2)
  507. {
  508. oldleader.dismount();
  509. }
  510. }
  511. }
  512. catch (Exception e)
  513. {
  514. _log.log(Level.WARNING, "Exception in setOwner: " + e.getMessage(), e);
  515. }
  516. oldOwner.setCastleId(0); // Unset has castle flag for old owner
  517. for (L2PcInstance member : oldOwner.getOnlineMembers(0))
  518. {
  519. removeResidentialSkills(member);
  520. member.sendSkillList();
  521. }
  522. }
  523. }
  524. updateOwnerInDB(clan); // Update in database
  525. setShowNpcCrest(false);
  526. // if clan have fortress, remove it
  527. if ((clan != null) && (clan.getFortId() > 0))
  528. {
  529. FortManager.getInstance().getFortByOwner(clan).removeOwner(true);
  530. }
  531. if (getSiege().getIsInProgress())
  532. {
  533. getSiege().midVictory(); // Mid victory phase of siege
  534. }
  535. TerritoryWarManager.getInstance().getTerritory(_castleId).setOwnerClan(clan);
  536. if (clan != null)
  537. {
  538. for (L2PcInstance member : clan.getOnlineMembers(0))
  539. {
  540. giveResidentialSkills(member);
  541. member.sendSkillList();
  542. }
  543. }
  544. }
  545. public void removeOwner(L2Clan clan)
  546. {
  547. if (clan != null)
  548. {
  549. _formerOwner = clan;
  550. if (Config.REMOVE_CASTLE_CIRCLETS)
  551. {
  552. CastleManager.getInstance().removeCirclet(_formerOwner, getCastleId());
  553. }
  554. for (L2PcInstance member : clan.getOnlineMembers(0))
  555. {
  556. removeResidentialSkills(member);
  557. member.sendSkillList();
  558. }
  559. clan.setCastleId(0);
  560. clan.broadcastToOnlineMembers(new PledgeShowInfoUpdate(clan));
  561. }
  562. updateOwnerInDB(null);
  563. if (getSiege().getIsInProgress())
  564. {
  565. getSiege().midVictory();
  566. }
  567. for (Integer fc : _function.keySet())
  568. {
  569. removeFunction(fc);
  570. }
  571. _function.clear();
  572. }
  573. // This method updates the castle tax rate
  574. public void setTaxPercent(L2PcInstance activeChar, int taxPercent)
  575. {
  576. int maxTax;
  577. switch (SevenSigns.getInstance().getSealOwner(SevenSigns.SEAL_STRIFE))
  578. {
  579. case SevenSigns.CABAL_DAWN:
  580. maxTax = 25;
  581. break;
  582. case SevenSigns.CABAL_DUSK:
  583. maxTax = 5;
  584. break;
  585. default: // no owner
  586. maxTax = 15;
  587. }
  588. if ((taxPercent < 0) || (taxPercent > maxTax))
  589. {
  590. activeChar.sendMessage("Tax value must be between 0 and " + maxTax + ".");
  591. return;
  592. }
  593. setTaxPercent(taxPercent);
  594. activeChar.sendMessage(getName() + " castle tax changed to " + taxPercent + "%.");
  595. }
  596. public void setTaxPercent(int taxPercent)
  597. {
  598. _taxPercent = taxPercent;
  599. _taxRate = _taxPercent / 100.0;
  600. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  601. PreparedStatement ps = con.prepareStatement("UPDATE castle SET taxPercent = ? WHERE id = ?"))
  602. {
  603. ps.setInt(1, taxPercent);
  604. ps.setInt(2, getCastleId());
  605. ps.execute();
  606. }
  607. catch (Exception e)
  608. {
  609. _log.log(Level.WARNING, e.getMessage(), e);
  610. }
  611. }
  612. /**
  613. * Respawn all doors on castle grounds.
  614. */
  615. public void spawnDoor()
  616. {
  617. spawnDoor(false);
  618. }
  619. /**
  620. * Respawn all doors on castle grounds<BR>
  621. * <BR>
  622. * @param isDoorWeak
  623. */
  624. public void spawnDoor(boolean isDoorWeak)
  625. {
  626. for (L2DoorInstance door : _doors)
  627. {
  628. if (door.isDead())
  629. {
  630. door.doRevive();
  631. if (isDoorWeak)
  632. {
  633. door.setCurrentHp(door.getMaxHp() / 2);
  634. }
  635. else
  636. {
  637. door.setCurrentHp(door.getMaxHp());
  638. }
  639. }
  640. if (door.getOpen())
  641. {
  642. door.closeMe();
  643. }
  644. }
  645. loadDoorUpgrade(); // Check for any upgrade the doors may have
  646. }
  647. // This method upgrade door
  648. public void upgradeDoor(int doorId, int hp, int pDef, int mDef)
  649. {
  650. L2DoorInstance door = getDoor(doorId);
  651. if (door == null)
  652. {
  653. return;
  654. }
  655. door.setCurrentHp(door.getMaxHp() + hp);
  656. saveDoorUpgrade(doorId, hp, pDef, mDef);
  657. }
  658. // This method loads castle
  659. private void load()
  660. {
  661. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  662. PreparedStatement ps1 = con.prepareStatement("SELECT * FROM castle WHERE id = ?");
  663. PreparedStatement ps2 = con.prepareStatement("SELECT clan_id FROM clan_data WHERE hasCastle = ?"))
  664. {
  665. ps1.setInt(1, getCastleId());
  666. try (ResultSet rs = ps1.executeQuery())
  667. {
  668. while (rs.next())
  669. {
  670. _name = rs.getString("name");
  671. // _OwnerId = rs.getInt("ownerId");
  672. _siegeDate = Calendar.getInstance();
  673. _siegeDate.setTimeInMillis(rs.getLong("siegeDate"));
  674. _siegeTimeRegistrationEndDate = Calendar.getInstance();
  675. _siegeTimeRegistrationEndDate.setTimeInMillis(rs.getLong("regTimeEnd"));
  676. _isTimeRegistrationOver = rs.getBoolean("regTimeOver");
  677. _taxPercent = rs.getInt("taxPercent");
  678. _treasury = rs.getLong("treasury");
  679. _showNpcCrest = rs.getBoolean("showNpcCrest");
  680. _ticketBuyCount = rs.getInt("ticketBuyCount");
  681. }
  682. }
  683. _taxRate = _taxPercent / 100.0;
  684. ps2.setInt(1, getCastleId());
  685. try (ResultSet rs = ps2.executeQuery())
  686. {
  687. while (rs.next())
  688. {
  689. _ownerId = rs.getInt("clan_id");
  690. }
  691. }
  692. if (getOwnerId() > 0)
  693. {
  694. L2Clan clan = ClanTable.getInstance().getClan(getOwnerId()); // Try to find clan instance
  695. ThreadPoolManager.getInstance().scheduleGeneral(new CastleUpdater(clan, 1), 3600000); // Schedule owner tasks to start running
  696. }
  697. }
  698. catch (Exception e)
  699. {
  700. _log.log(Level.WARNING, "Exception: loadCastleData(): " + e.getMessage(), e);
  701. }
  702. }
  703. /** Load All Functions */
  704. private void loadFunctions()
  705. {
  706. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  707. PreparedStatement ps = con.prepareStatement("SELECT * FROM castle_functions WHERE castle_id = ?"))
  708. {
  709. ps.setInt(1, getCastleId());
  710. try (ResultSet rs = ps.executeQuery())
  711. {
  712. while (rs.next())
  713. {
  714. _function.put(rs.getInt("type"), new CastleFunction(rs.getInt("type"), rs.getInt("lvl"), rs.getInt("lease"), 0, rs.getLong("rate"), rs.getLong("endTime"), true));
  715. }
  716. }
  717. }
  718. catch (Exception e)
  719. {
  720. _log.log(Level.SEVERE, "Exception: Castle.loadFunctions(): " + e.getMessage(), e);
  721. }
  722. }
  723. /**
  724. * Remove function In List and in DB
  725. * @param functionType
  726. */
  727. public void removeFunction(int functionType)
  728. {
  729. _function.remove(functionType);
  730. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  731. PreparedStatement ps = con.prepareStatement("DELETE FROM castle_functions WHERE castle_id=? AND type=?"))
  732. {
  733. ps.setInt(1, getCastleId());
  734. ps.setInt(2, functionType);
  735. ps.execute();
  736. }
  737. catch (Exception e)
  738. {
  739. _log.log(Level.SEVERE, "Exception: Castle.removeFunctions(int functionType): " + e.getMessage(), e);
  740. }
  741. }
  742. public boolean updateFunctions(L2PcInstance player, int type, int lvl, int lease, long rate, boolean addNew)
  743. {
  744. if (player == null)
  745. {
  746. return false;
  747. }
  748. if (lease > 0)
  749. {
  750. if (!player.destroyItemByItemId("Consume", PcInventory.ADENA_ID, lease, null, true))
  751. {
  752. return false;
  753. }
  754. }
  755. if (addNew)
  756. {
  757. _function.put(type, new CastleFunction(type, lvl, lease, 0, rate, 0, false));
  758. }
  759. else
  760. {
  761. if ((lvl == 0) && (lease == 0))
  762. {
  763. removeFunction(type);
  764. }
  765. else
  766. {
  767. int diffLease = lease - _function.get(type).getLease();
  768. if (diffLease > 0)
  769. {
  770. _function.remove(type);
  771. _function.put(type, new CastleFunction(type, lvl, lease, 0, rate, -1, false));
  772. }
  773. else
  774. {
  775. _function.get(type).setLease(lease);
  776. _function.get(type).setLvl(lvl);
  777. _function.get(type).dbSave();
  778. }
  779. }
  780. }
  781. return true;
  782. }
  783. public void activateInstance()
  784. {
  785. loadDoor();
  786. }
  787. // This method loads castle door data from database
  788. private void loadDoor()
  789. {
  790. for (L2DoorInstance door : DoorTable.getInstance().getDoors())
  791. {
  792. if ((door.getCastle() != null) && (door.getCastle().getCastleId() == getCastleId()))
  793. {
  794. _doors.add(door);
  795. }
  796. }
  797. }
  798. // This method loads castle door upgrade data from database
  799. private void loadDoorUpgrade()
  800. {
  801. StringBuilder doorIds = new StringBuilder(100);
  802. for (L2DoorInstance door : getDoors())
  803. {
  804. doorIds.append(door.getDoorId()).append(',');
  805. }
  806. doorIds.deleteCharAt(doorIds.length() - 1);
  807. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  808. Statement s = con.createStatement();
  809. ResultSet rs = s.executeQuery("SELECT * FROM castle_doorupgrade WHERE doorId IN (" + doorIds.toString() + ")"))
  810. {
  811. while (rs.next())
  812. {
  813. upgradeDoor(rs.getInt("id"), rs.getInt("hp"), rs.getInt("pDef"), rs.getInt("mDef"));
  814. }
  815. }
  816. catch (Exception e)
  817. {
  818. _log.log(Level.WARNING, "Exception: loadCastleDoorUpgrade(): " + e.getMessage(), e);
  819. }
  820. }
  821. private void removeDoorUpgrade()
  822. {
  823. StringBuilder doorIds = new StringBuilder(100);
  824. for (L2DoorInstance door : getDoors())
  825. {
  826. doorIds.append(door.getDoorId()).append(',');
  827. }
  828. doorIds.deleteCharAt(doorIds.length() - 1);
  829. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  830. Statement s = con.createStatement())
  831. {
  832. s.executeQuery("DELETE FROM castle_doorupgrade WHERE doorId IN (" + doorIds.toString() + ")");
  833. }
  834. catch (Exception e)
  835. {
  836. _log.log(Level.WARNING, "Exception: removeDoorUpgrade(): " + e.getMessage(), e);
  837. }
  838. }
  839. private void saveDoorUpgrade(int doorId, int hp, int pDef, int mDef)
  840. {
  841. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  842. PreparedStatement ps = con.prepareStatement("INSERT INTO castle_doorupgrade (doorId, hp, pDef, mDef) values (?,?,?,?)"))
  843. {
  844. ps.setInt(1, doorId);
  845. ps.setInt(2, hp);
  846. ps.setInt(3, pDef);
  847. ps.setInt(4, mDef);
  848. ps.execute();
  849. }
  850. catch (Exception e)
  851. {
  852. _log.log(Level.WARNING, "Exception: saveDoorUpgrade(int doorId, int hp, int pDef, int mDef): " + e.getMessage(), e);
  853. }
  854. }
  855. private void updateOwnerInDB(L2Clan clan)
  856. {
  857. if (clan != null)
  858. {
  859. _ownerId = clan.getClanId(); // Update owner id property
  860. }
  861. else
  862. {
  863. _ownerId = 0; // Remove owner
  864. resetManor();
  865. }
  866. try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  867. {
  868. // NEED TO REMOVE HAS CASTLE FLAG FROM CLAN_DATA
  869. // SHOULD BE CHECKED FROM CASTLE TABLE
  870. PreparedStatement statement = con.prepareStatement("UPDATE clan_data SET hasCastle = 0 WHERE hasCastle = ?");
  871. statement.setInt(1, getCastleId());
  872. statement.execute();
  873. statement.close();
  874. statement = con.prepareStatement("UPDATE clan_data SET hasCastle = ? WHERE clan_id = ?");
  875. statement.setInt(1, getCastleId());
  876. statement.setInt(2, getOwnerId());
  877. statement.execute();
  878. statement.close();
  879. // Announce to clan members
  880. if (clan != null)
  881. {
  882. clan.setCastleId(getCastleId()); // Set has castle flag for new owner
  883. clan.broadcastToOnlineMembers(new PledgeShowInfoUpdate(clan));
  884. clan.broadcastToOnlineMembers(new PlaySound(1, "Siege_Victory", 0, 0, 0, 0, 0));
  885. ThreadPoolManager.getInstance().scheduleGeneral(new CastleUpdater(clan, 1), 3600000); // Schedule owner tasks to start running
  886. }
  887. }
  888. catch (Exception e)
  889. {
  890. _log.log(Level.WARNING, "Exception: updateOwnerInDB(L2Clan clan): " + e.getMessage(), e);
  891. }
  892. }
  893. public final int getCastleId()
  894. {
  895. return _castleId;
  896. }
  897. public final L2DoorInstance getDoor(int doorId)
  898. {
  899. if (doorId <= 0)
  900. {
  901. return null;
  902. }
  903. for (L2DoorInstance door : getDoors())
  904. {
  905. if (door.getDoorId() == doorId)
  906. {
  907. return door;
  908. }
  909. }
  910. return null;
  911. }
  912. public final List<L2DoorInstance> getDoors()
  913. {
  914. return _doors;
  915. }
  916. public final String getName()
  917. {
  918. return _name;
  919. }
  920. public final int getOwnerId()
  921. {
  922. return _ownerId;
  923. }
  924. public final Siege getSiege()
  925. {
  926. if (_siege == null)
  927. {
  928. _siege = new Siege(new Castle[]
  929. {
  930. this
  931. });
  932. }
  933. return _siege;
  934. }
  935. public final Calendar getSiegeDate()
  936. {
  937. return _siegeDate;
  938. }
  939. public boolean getIsTimeRegistrationOver()
  940. {
  941. return _isTimeRegistrationOver;
  942. }
  943. public void setIsTimeRegistrationOver(boolean val)
  944. {
  945. _isTimeRegistrationOver = val;
  946. }
  947. public Calendar getTimeRegistrationOverDate()
  948. {
  949. if (_siegeTimeRegistrationEndDate == null)
  950. {
  951. _siegeTimeRegistrationEndDate = Calendar.getInstance();
  952. }
  953. return _siegeTimeRegistrationEndDate;
  954. }
  955. public final int getTaxPercent()
  956. {
  957. return _taxPercent;
  958. }
  959. public final double getTaxRate()
  960. {
  961. return _taxRate;
  962. }
  963. public final long getTreasury()
  964. {
  965. return _treasury;
  966. }
  967. public final boolean getShowNpcCrest()
  968. {
  969. return _showNpcCrest;
  970. }
  971. public final void setShowNpcCrest(boolean showNpcCrest)
  972. {
  973. if (_showNpcCrest != showNpcCrest)
  974. {
  975. _showNpcCrest = showNpcCrest;
  976. updateShowNpcCrest();
  977. }
  978. }
  979. public List<SeedProduction> getSeedProduction(int period)
  980. {
  981. return (period == CastleManorManager.PERIOD_CURRENT ? _production : _productionNext);
  982. }
  983. public List<CropProcure> getCropProcure(int period)
  984. {
  985. return (period == CastleManorManager.PERIOD_CURRENT ? _procure : _procureNext);
  986. }
  987. public void setSeedProduction(List<SeedProduction> seed, int period)
  988. {
  989. if (period == CastleManorManager.PERIOD_CURRENT)
  990. {
  991. _production = seed;
  992. }
  993. else
  994. {
  995. _productionNext = seed;
  996. }
  997. }
  998. public void setCropProcure(List<CropProcure> crop, int period)
  999. {
  1000. if (period == CastleManorManager.PERIOD_CURRENT)
  1001. {
  1002. _procure = crop;
  1003. }
  1004. else
  1005. {
  1006. _procureNext = crop;
  1007. }
  1008. }
  1009. public SeedProduction getSeed(int seedId, int period)
  1010. {
  1011. for (SeedProduction seed : getSeedProduction(period))
  1012. {
  1013. if (seed.getId() == seedId)
  1014. {
  1015. return seed;
  1016. }
  1017. }
  1018. return null;
  1019. }
  1020. public CropProcure getCrop(int cropId, int period)
  1021. {
  1022. for (CropProcure crop : getCropProcure(period))
  1023. {
  1024. if (crop.getId() == cropId)
  1025. {
  1026. return crop;
  1027. }
  1028. }
  1029. return null;
  1030. }
  1031. public long getManorCost(int period)
  1032. {
  1033. List<CropProcure> procure;
  1034. List<SeedProduction> production;
  1035. if (period == CastleManorManager.PERIOD_CURRENT)
  1036. {
  1037. procure = _procure;
  1038. production = _production;
  1039. }
  1040. else
  1041. {
  1042. procure = _procureNext;
  1043. production = _productionNext;
  1044. }
  1045. long total = 0;
  1046. if (production != null)
  1047. {
  1048. for (SeedProduction seed : production)
  1049. {
  1050. total += ManorData.getInstance().getSeedBuyPrice(seed.getId()) * seed.getStartProduce();
  1051. }
  1052. }
  1053. if (procure != null)
  1054. {
  1055. for (CropProcure crop : procure)
  1056. {
  1057. total += crop.getPrice() * crop.getStartAmount();
  1058. }
  1059. }
  1060. return total;
  1061. }
  1062. // save manor production data
  1063. public void saveSeedData()
  1064. {
  1065. try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  1066. {
  1067. try (PreparedStatement ps1 = con.prepareStatement(CASTLE_MANOR_DELETE_PRODUCTION))
  1068. {
  1069. ps1.setInt(1, getCastleId());
  1070. ps1.execute();
  1071. }
  1072. if (_production != null)
  1073. {
  1074. int count = 0;
  1075. StringBuilder query = new StringBuilder();
  1076. query.append("INSERT INTO castle_manor_production VALUES ");
  1077. String values[] = new String[_production.size()];
  1078. for (SeedProduction s : _production)
  1079. {
  1080. values[count++] = "(" + getCastleId() + "," + s.getId() + "," + s.getCanProduce() + "," + s.getStartProduce() + "," + s.getPrice() + "," + CastleManorManager.PERIOD_CURRENT + ")";
  1081. }
  1082. if (values.length > 0)
  1083. {
  1084. query.append(values[0]);
  1085. for (int i = 1; i < values.length; i++)
  1086. {
  1087. query.append(',');
  1088. query.append(values[i]);
  1089. }
  1090. try (PreparedStatement ps2 = con.prepareStatement(query.toString()))
  1091. {
  1092. ps2.execute();
  1093. }
  1094. }
  1095. }
  1096. if (_productionNext != null)
  1097. {
  1098. int count = 0;
  1099. String query = "INSERT INTO castle_manor_production VALUES ";
  1100. String values[] = new String[_productionNext.size()];
  1101. for (SeedProduction s : _productionNext)
  1102. {
  1103. values[count++] = "(" + getCastleId() + "," + s.getId() + "," + s.getCanProduce() + "," + s.getStartProduce() + "," + s.getPrice() + "," + CastleManorManager.PERIOD_NEXT + ")";
  1104. }
  1105. if (values.length > 0)
  1106. {
  1107. query += values[0];
  1108. for (int i = 1; i < values.length; i++)
  1109. {
  1110. query += "," + values[i];
  1111. }
  1112. try (PreparedStatement ps3 = con.prepareStatement(query))
  1113. {
  1114. ps3.execute();
  1115. }
  1116. }
  1117. }
  1118. }
  1119. catch (Exception e)
  1120. {
  1121. _log.info("Error adding seed production data for castle " + getName() + ": " + e.getMessage());
  1122. }
  1123. }
  1124. // save manor production data for specified period
  1125. public void saveSeedData(int period)
  1126. {
  1127. try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  1128. {
  1129. PreparedStatement statement = con.prepareStatement(CASTLE_MANOR_DELETE_PRODUCTION_PERIOD);
  1130. statement.setInt(1, getCastleId());
  1131. statement.setInt(2, period);
  1132. statement.execute();
  1133. statement.close();
  1134. List<SeedProduction> prod = null;
  1135. prod = getSeedProduction(period);
  1136. if (prod != null)
  1137. {
  1138. int count = 0;
  1139. StringBuilder query = new StringBuilder();
  1140. query.append("INSERT INTO castle_manor_production VALUES ");
  1141. String values[] = new String[prod.size()];
  1142. for (SeedProduction s : prod)
  1143. {
  1144. values[count++] = "(" + getCastleId() + "," + s.getId() + "," + s.getCanProduce() + "," + s.getStartProduce() + "," + s.getPrice() + "," + period + ")";
  1145. }
  1146. if (values.length > 0)
  1147. {
  1148. query.append(values[0]);
  1149. for (int i = 1; i < values.length; i++)
  1150. {
  1151. query.append(',').append(values[i]);
  1152. }
  1153. statement = con.prepareStatement(query.toString());
  1154. statement.execute();
  1155. statement.close();
  1156. }
  1157. }
  1158. }
  1159. catch (Exception e)
  1160. {
  1161. _log.info("Error adding seed production data for castle " + getName() + ": " + e.getMessage());
  1162. }
  1163. }
  1164. // save crop procure data
  1165. public void saveCropData()
  1166. {
  1167. try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  1168. {
  1169. try (PreparedStatement ps1 = con.prepareStatement(CASTLE_MANOR_DELETE_PROCURE))
  1170. {
  1171. ps1.setInt(1, getCastleId());
  1172. ps1.execute();
  1173. }
  1174. if (!_procure.isEmpty())
  1175. {
  1176. int count = 0;
  1177. StringBuilder query = new StringBuilder();
  1178. query.append("INSERT INTO castle_manor_procure VALUES ");
  1179. String values[] = new String[_procure.size()];
  1180. for (CropProcure cp : _procure)
  1181. {
  1182. values[count++] = "(" + getCastleId() + "," + cp.getId() + "," + cp.getAmount() + "," + cp.getStartAmount() + "," + cp.getPrice() + "," + cp.getReward() + "," + CastleManorManager.PERIOD_CURRENT + ")";
  1183. }
  1184. if (values.length > 0)
  1185. {
  1186. query.append(values[0]);
  1187. for (int i = 1; i < values.length; i++)
  1188. {
  1189. query.append(',');
  1190. query.append(values[i]);
  1191. }
  1192. try (PreparedStatement ps2 = con.prepareStatement(query.toString()))
  1193. {
  1194. ps2.execute();
  1195. }
  1196. }
  1197. }
  1198. if (!_procureNext.isEmpty())
  1199. {
  1200. int count = 0;
  1201. String query = "INSERT INTO castle_manor_procure VALUES ";
  1202. String values[] = new String[_procureNext.size()];
  1203. for (CropProcure cp : _procureNext)
  1204. {
  1205. values[count++] = "(" + getCastleId() + "," + cp.getId() + "," + cp.getAmount() + "," + cp.getStartAmount() + "," + cp.getPrice() + "," + cp.getReward() + "," + CastleManorManager.PERIOD_NEXT + ")";
  1206. }
  1207. if (values.length > 0)
  1208. {
  1209. query += values[0];
  1210. for (int i = 1; i < values.length; i++)
  1211. {
  1212. query += "," + values[i];
  1213. }
  1214. try (PreparedStatement ps3 = con.prepareStatement(query))
  1215. {
  1216. ps3.execute();
  1217. }
  1218. }
  1219. }
  1220. }
  1221. catch (Exception e)
  1222. {
  1223. _log.info("Error adding crop data for castle " + getName() + ": " + e.getMessage());
  1224. }
  1225. }
  1226. // save crop procure data for specified period
  1227. public void saveCropData(int period)
  1228. {
  1229. try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  1230. {
  1231. PreparedStatement statement = con.prepareStatement(CASTLE_MANOR_DELETE_PROCURE_PERIOD);
  1232. statement.setInt(1, getCastleId());
  1233. statement.setInt(2, period);
  1234. statement.execute();
  1235. statement.close();
  1236. List<CropProcure> proc = null;
  1237. proc = getCropProcure(period);
  1238. if ((proc != null) && (proc.size() > 0))
  1239. {
  1240. int count = 0;
  1241. StringBuilder query = new StringBuilder();
  1242. query.append("INSERT INTO castle_manor_procure VALUES ");
  1243. String values[] = new String[proc.size()];
  1244. for (CropProcure cp : proc)
  1245. {
  1246. values[count++] = "(" + getCastleId() + "," + cp.getId() + "," + cp.getAmount() + "," + cp.getStartAmount() + "," + cp.getPrice() + "," + cp.getReward() + "," + period + ")";
  1247. }
  1248. if (values.length > 0)
  1249. {
  1250. query.append(values[0]);
  1251. for (int i = 1; i < values.length; i++)
  1252. {
  1253. query.append(',');
  1254. query.append(values[i]);
  1255. }
  1256. statement = con.prepareStatement(query.toString());
  1257. statement.execute();
  1258. statement.close();
  1259. }
  1260. }
  1261. }
  1262. catch (Exception e)
  1263. {
  1264. _log.info("Error adding crop data for castle " + getName() + ": " + e.getMessage());
  1265. }
  1266. }
  1267. public void updateCrop(int cropId, long amount, int period)
  1268. {
  1269. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  1270. PreparedStatement ps = con.prepareStatement(CASTLE_UPDATE_CROP))
  1271. {
  1272. ps.setLong(1, amount);
  1273. ps.setInt(2, cropId);
  1274. ps.setInt(3, getCastleId());
  1275. ps.setInt(4, period);
  1276. ps.execute();
  1277. }
  1278. catch (Exception e)
  1279. {
  1280. _log.info("Error adding crop data for castle " + getName() + ": " + e.getMessage());
  1281. }
  1282. }
  1283. public void updateSeed(int seedId, long amount, int period)
  1284. {
  1285. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  1286. PreparedStatement ps = con.prepareStatement(CASTLE_UPDATE_SEED))
  1287. {
  1288. ps.setLong(1, amount);
  1289. ps.setInt(2, seedId);
  1290. ps.setInt(3, getCastleId());
  1291. ps.setInt(4, period);
  1292. ps.execute();
  1293. }
  1294. catch (Exception e)
  1295. {
  1296. _log.info("Error adding seed production data for castle " + getName() + ": " + e.getMessage());
  1297. }
  1298. }
  1299. public boolean isNextPeriodApproved()
  1300. {
  1301. return _isNextPeriodApproved;
  1302. }
  1303. public void setNextPeriodApproved(boolean val)
  1304. {
  1305. _isNextPeriodApproved = val;
  1306. }
  1307. public void updateClansReputation()
  1308. {
  1309. if (_formerOwner != null)
  1310. {
  1311. if (_formerOwner != ClanTable.getInstance().getClan(getOwnerId()))
  1312. {
  1313. int maxreward = Math.max(0, _formerOwner.getReputationScore());
  1314. _formerOwner.takeReputationScore(Config.LOOSE_CASTLE_POINTS, true);
  1315. L2Clan owner = ClanTable.getInstance().getClan(getOwnerId());
  1316. if (owner != null)
  1317. {
  1318. owner.addReputationScore(Math.min(Config.TAKE_CASTLE_POINTS, maxreward), true);
  1319. }
  1320. }
  1321. else
  1322. {
  1323. _formerOwner.addReputationScore(Config.CASTLE_DEFENDED_POINTS, true);
  1324. }
  1325. }
  1326. else
  1327. {
  1328. L2Clan owner = ClanTable.getInstance().getClan(getOwnerId());
  1329. if (owner != null)
  1330. {
  1331. owner.addReputationScore(Config.TAKE_CASTLE_POINTS, true);
  1332. }
  1333. }
  1334. }
  1335. public void updateShowNpcCrest()
  1336. {
  1337. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  1338. PreparedStatement ps = con.prepareStatement("UPDATE castle SET showNpcCrest = ? WHERE id = ?"))
  1339. {
  1340. ps.setString(1, String.valueOf(getShowNpcCrest()));
  1341. ps.setInt(2, getCastleId());
  1342. ps.execute();
  1343. }
  1344. catch (Exception e)
  1345. {
  1346. _log.info("Error saving showNpcCrest for castle " + getName() + ": " + e.getMessage());
  1347. }
  1348. }
  1349. public List<L2Skill> getResidentialSkills()
  1350. {
  1351. return _residentialSkills;
  1352. }
  1353. public void giveResidentialSkills(L2PcInstance player)
  1354. {
  1355. for (L2Skill sk : _residentialSkills)
  1356. {
  1357. player.addSkill(sk, false);
  1358. }
  1359. Territory territory = TerritoryWarManager.getInstance().getTerritory(getCastleId());
  1360. if ((territory != null) && territory.getOwnedWardIds().contains(getCastleId() + 80))
  1361. {
  1362. for (int wardId : territory.getOwnedWardIds())
  1363. {
  1364. final List<L2SkillLearn> territorySkills = SkillTreesData.getInstance().getAvailableResidentialSkills(wardId);
  1365. for (L2SkillLearn s : territorySkills)
  1366. {
  1367. final L2Skill sk = SkillTable.getInstance().getInfo(s.getSkillId(), s.getSkillLevel());
  1368. if (sk != null)
  1369. {
  1370. player.addSkill(sk, false);
  1371. }
  1372. else
  1373. {
  1374. _log.warning("Trying to add a null skill for Territory Ward Id: " + wardId + ", skill Id: " + s.getSkillId() + " level: " + s.getSkillLevel() + "!");
  1375. }
  1376. }
  1377. }
  1378. }
  1379. }
  1380. public void removeResidentialSkills(L2PcInstance player)
  1381. {
  1382. for (L2Skill sk : _residentialSkills)
  1383. {
  1384. player.removeSkill(sk, false, true);
  1385. }
  1386. if (TerritoryWarManager.getInstance().getTerritory(getCastleId()) != null)
  1387. {
  1388. for (int wardId : TerritoryWarManager.getInstance().getTerritory(getCastleId()).getOwnedWardIds())
  1389. {
  1390. final List<L2SkillLearn> territorySkills = SkillTreesData.getInstance().getAvailableResidentialSkills(wardId);
  1391. for (L2SkillLearn s : territorySkills)
  1392. {
  1393. final L2Skill sk = SkillTable.getInstance().getInfo(s.getSkillId(), s.getSkillLevel());
  1394. if (sk != null)
  1395. {
  1396. player.removeSkill(sk, false, true);
  1397. }
  1398. else
  1399. {
  1400. _log.warning("Trying to remove a null skill for Territory Ward Id: " + wardId + ", skill Id: " + s.getSkillId() + " level: " + s.getSkillLevel() + "!");
  1401. }
  1402. }
  1403. }
  1404. }
  1405. }
  1406. /**
  1407. * Register Artefact to castle
  1408. * @param artefact
  1409. */
  1410. public void registerArtefact(L2ArtefactInstance artefact)
  1411. {
  1412. _artefacts.add(artefact);
  1413. }
  1414. public List<L2ArtefactInstance> getArtefacts()
  1415. {
  1416. return _artefacts;
  1417. }
  1418. public void resetManor()
  1419. {
  1420. setCropProcure(new ArrayList<CropProcure>(), CastleManorManager.PERIOD_CURRENT);
  1421. setCropProcure(new ArrayList<CropProcure>(), CastleManorManager.PERIOD_NEXT);
  1422. setSeedProduction(new ArrayList<SeedProduction>(), CastleManorManager.PERIOD_CURRENT);
  1423. setSeedProduction(new ArrayList<SeedProduction>(), CastleManorManager.PERIOD_NEXT);
  1424. if (Config.ALT_MANOR_SAVE_ALL_ACTIONS)
  1425. {
  1426. saveCropData();
  1427. saveSeedData();
  1428. }
  1429. }
  1430. /**
  1431. * @return the tickets exchanged for this castle
  1432. */
  1433. public int getTicketBuyCount()
  1434. {
  1435. return _ticketBuyCount;
  1436. }
  1437. /**
  1438. * Set the exchanged tickets count.<br>
  1439. * Performs database update.
  1440. * @param count the ticket count to set
  1441. */
  1442. public void setTicketBuyCount(int count)
  1443. {
  1444. _ticketBuyCount = count;
  1445. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  1446. PreparedStatement statement = con.prepareStatement("UPDATE castle SET ticketBuyCount = ? WHERE id = ?"))
  1447. {
  1448. statement.setInt(1, _ticketBuyCount);
  1449. statement.setInt(2, _castleId);
  1450. statement.execute();
  1451. }
  1452. catch (Exception e)
  1453. {
  1454. _log.log(Level.WARNING, e.getMessage(), e);
  1455. }
  1456. }
  1457. @Override
  1458. public String toString()
  1459. {
  1460. return _name + "(" + _castleId + ")";
  1461. }
  1462. }