Castle.java 41 KB

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