001package com.fs.starfarer.api.impl.campaign.intel;
002
003import java.util.List;
004import java.util.Map;
005import java.util.Set;
006
007import java.awt.Color;
008
009import org.apache.log4j.Logger;
010import org.lwjgl.util.vector.Vector2f;
011
012import com.fs.starfarer.api.Global;
013import com.fs.starfarer.api.campaign.CampaignFleetAPI;
014import com.fs.starfarer.api.campaign.CargoAPI;
015import com.fs.starfarer.api.campaign.FactionAPI;
016import com.fs.starfarer.api.campaign.InteractionDialogAPI;
017import com.fs.starfarer.api.campaign.PlanetAPI;
018import com.fs.starfarer.api.campaign.RepLevel;
019import com.fs.starfarer.api.campaign.ReputationActionResponsePlugin.ReputationAdjustmentResult;
020import com.fs.starfarer.api.campaign.SectorEntityToken;
021import com.fs.starfarer.api.campaign.econ.MarketAPI;
022import com.fs.starfarer.api.campaign.econ.MarketAPI.SurveyLevel;
023import com.fs.starfarer.api.campaign.listeners.SurveyPlanetListener;
024import com.fs.starfarer.api.campaign.rules.MemoryAPI;
025import com.fs.starfarer.api.impl.campaign.CoreReputationPlugin;
026import com.fs.starfarer.api.impl.campaign.CoreReputationPlugin.MissionCompletionRep;
027import com.fs.starfarer.api.impl.campaign.CoreReputationPlugin.RepActionEnvelope;
028import com.fs.starfarer.api.impl.campaign.CoreReputationPlugin.RepActions;
029import com.fs.starfarer.api.impl.campaign.CoreReputationPlugin.RepRewards;
030import com.fs.starfarer.api.impl.campaign.ids.Factions;
031import com.fs.starfarer.api.impl.campaign.ids.MemFlags;
032import com.fs.starfarer.api.impl.campaign.ids.Tags;
033import com.fs.starfarer.api.ui.SectorMapAPI;
034import com.fs.starfarer.api.ui.TooltipMakerAPI;
035import com.fs.starfarer.api.util.Misc;
036import com.fs.starfarer.api.util.Misc.Token;
037import com.fs.starfarer.api.util.WeightedRandomPicker;
038
039public class SurveyPlanetMissionIntel extends BaseMissionIntel implements SurveyPlanetListener {
040        public static Logger log = Global.getLogger(SurveyPlanetMissionIntel.class);
041        
042        protected int reward;
043        protected FactionAPI faction;
044        protected MarketAPI market;
045        
046        protected PlanetAPI planet;
047
048
049        
050        public SurveyPlanetMissionIntel(PlanetAPI planet) {
051                this.planet = planet;
052                
053                WeightedRandomPicker<MarketAPI> marketPicker = new WeightedRandomPicker<MarketAPI>();
054                for (MarketAPI market : Global.getSector().getEconomy().getMarketsCopy()) {
055                        if (market.isHidden()) continue;
056                        if (market.getFaction().isPlayerFaction()) continue;
057                        
058                        marketPicker.add(market, market.getSize());
059                }
060                
061                market = marketPicker.pick();
062                if (market == null) {
063                        endImmediately();
064                        return;
065                }
066                
067                faction = market.getFaction();
068                if (!market.getFaction().isHostileTo(Factions.INDEPENDENT) && (float) Math.random() > 0.67f) {
069                        faction = Global.getSector().getFaction(Factions.INDEPENDENT);
070                }
071                
072                setDuration(120f);
073                
074                reward = (int) Misc.getDistance(new Vector2f(), planet.getLocationInHyperspace());
075                //reward *= 1.25f;
076                reward = 20000 + (reward / 10000) * 10000;
077                if (reward < 10000) reward = 10000;
078                
079                
080                log.info("Created SurveyPlanetMissionIntel: " + planet.getName() + ", faction: " + faction.getDisplayName());
081
082                
083                initRandomCancel();
084                setPostingLocation(market.getPrimaryEntity());
085                
086                Global.getSector().getIntelManager().queueIntel(this);
087                
088        }
089
090
091        public PlanetAPI getPlanet() {
092                return planet;
093        }
094
095
096        @Override
097        protected MissionResult createAbandonedResult(boolean withPenalty) {
098                if (withPenalty) {
099                        MissionCompletionRep rep = new MissionCompletionRep(RepRewards.HIGH, RepLevel.WELCOMING,
100                                         -RepRewards.TINY, RepLevel.INHOSPITABLE);
101                        ReputationAdjustmentResult result = Global.getSector().adjustPlayerReputation(
102                                new RepActionEnvelope(RepActions.MISSION_FAILURE, rep,
103                                                                          null, null, true, false),
104                                                                          faction.getId());
105                        return new MissionResult(0, result);
106                }
107                return new MissionResult();
108        }
109
110
111        @Override
112        protected MissionResult createTimeRanOutFailedResult() {
113                return createAbandonedResult(true);
114        }
115
116
117        @Override
118        public void missionAccepted() {
119                planet.getMemoryWithoutUpdate().set("$spm_target", true, getDuration());
120                planet.getMemoryWithoutUpdate().set("$spm_eventRef", this, getDuration());
121                Misc.setFlagWithReason(planet.getMemoryWithoutUpdate(), MemFlags.ENTITY_MISSION_IMPORTANT,
122                                                       "spm", true, getDuration());     
123                
124                Global.getSector().getListenerManager().addListener(this);
125        }
126        
127        
128        @Override
129        public void endMission() {
130                planet.getMemoryWithoutUpdate().unset("$spm_target");
131                planet.getMemoryWithoutUpdate().unset("$spm_eventRef");
132                Misc.setFlagWithReason(planet.getMemoryWithoutUpdate(), MemFlags.ENTITY_MISSION_IMPORTANT,
133                                                          "spm", false, 0f);
134                Global.getSector().getListenerManager().removeListener(this);
135                
136                endAfterDelay();
137        }
138
139        @Override
140        public void advanceMission(float amount) {
141                if (planet.getMarket() != null && planet.getMarket().getSurveyLevel() == SurveyLevel.FULL) {
142                        reportPlayerSurveyedPlanet(planet);
143                }
144        }
145
146        @Override
147        public boolean callEvent(String ruleId, final InteractionDialogAPI dialog, List<Token> params, Map<String, MemoryAPI> memoryMap) {
148                String action = params.get(0).getString(memoryMap);
149                
150                CampaignFleetAPI playerFleet = Global.getSector().getPlayerFleet();
151                CargoAPI cargo = playerFleet.getCargo();
152                
153//              if (action.equals("finishedSurvey")) {
154//                      AddRemoveCommodity.addCreditsGainText(reward, dialog.getTextPanel());
155//                      cargo.getCredits().add(reward);
156//                      
157//                      MissionCompletionRep rep = new MissionCompletionRep(RepRewards.HIGH, RepLevel.WELCOMING,
158//                                       -RepRewards.TINY, RepLevel.INHOSPITABLE);
159//
160//                      ReputationAdjustmentResult result = Global.getSector().adjustPlayerReputation(
161//                                      new RepActionEnvelope(RepActions.MISSION_SUCCESS, rep,
162//                                                                                null, dialog.getTextPanel(), true, false), 
163//                                                                                faction.getId());
164//                      setMissionResult(new MissionResult(reward, result));
165//                      setMissionState(MissionState.COMPLETED);
166//                      endMission();
167//              }
168                
169                return true;
170        }
171        
172        public void reportPlayerSurveyedPlanet(PlanetAPI planet) {
173                if (planet != this.planet) return;
174                
175                CampaignFleetAPI playerFleet = Global.getSector().getPlayerFleet();
176                CargoAPI cargo = playerFleet.getCargo();
177                
178                cargo.getCredits().add(reward);
179                
180                MissionCompletionRep rep = new MissionCompletionRep(RepRewards.HIGH, RepLevel.WELCOMING,
181                                 -RepRewards.TINY, RepLevel.INHOSPITABLE);
182
183                ReputationAdjustmentResult result = Global.getSector().adjustPlayerReputation(
184                                new RepActionEnvelope(RepActions.MISSION_SUCCESS, rep,
185                                                                          null, null, true, false), 
186                                                                          faction.getId());
187                setMissionResult(new MissionResult(reward, result));
188                setMissionState(MissionState.COMPLETED);
189                endMission();
190                sendUpdateIfPlayerHasIntel(missionResult, false);
191        }
192
193        
194        
195        
196        
197        protected void addBulletPoints(TooltipMakerAPI info, ListInfoMode mode) {
198                
199                Color h = Misc.getHighlightColor();
200                Color g = Misc.getGrayColor();
201                float pad = 3f;
202                float opad = 10f;
203                
204                float initPad = pad;
205                if (mode == ListInfoMode.IN_DESC) initPad = opad;
206                
207                Color tc = getBulletColorForMode(mode);
208                
209                bullet(info);
210                boolean isUpdate = getListInfoParam() != null;
211                
212                if (isUpdate) {
213                        // 3 possible updates: de-posted/expired, failed, completed
214                        if (isFailed() || isCancelled()) {
215                                return;
216                        } else if (isCompleted()) {
217                                if (missionResult.payment > 0) {
218                                        info.addPara("%s received", initPad, tc, h, Misc.getDGSCredits(missionResult.payment));
219                                }
220                                CoreReputationPlugin.addAdjustmentMessage(missionResult.rep1.delta, faction, null, 
221                                                                                                                  null, null, info, tc, isUpdate, 0f);
222                        }
223                } else {
224                        // either in small description, or in tooltip/intel list
225                        if (missionResult != null) {
226                                if (missionResult.payment > 0) {
227                                        info.addPara("%s received", initPad, tc, h, Misc.getDGSCredits(missionResult.payment));
228                                        initPad = 0f;
229                                }
230                                
231                                if (missionResult.rep1 != null) {
232                                        CoreReputationPlugin.addAdjustmentMessage(missionResult.rep1.delta, faction, null, 
233                                                                                                          null, null, info, tc, isUpdate, initPad);
234                                        initPad = 0f;
235                                }
236                        } else {
237                                float betweenPad = 0f;
238                                if (mode != ListInfoMode.IN_DESC) {
239                                        info.addPara("Faction: " + faction.getDisplayName(), initPad, tc,
240                                                                                                 faction.getBaseUIColor(),
241                                                                                                 faction.getDisplayName());
242                                        initPad = betweenPad;
243                                } else {
244                                        betweenPad = 0f;
245                                }
246                                
247                                info.addPara("%s reward", initPad, tc, h, Misc.getDGSCredits(reward));
248                                addDays(info, "to complete", duration - elapsedDays, tc, betweenPad);
249                        }
250                }
251                
252                unindent(info);
253        }
254        
255        @Override
256        public void createIntelInfo(TooltipMakerAPI info, ListInfoMode mode) {
257                Color c = getTitleColor(mode);
258                info.addPara(getName(), c, 0f);
259                
260                addBulletPoints(info, mode);
261        }
262        
263        public String getSortString() {
264                //return "Survey";
265                return super.getSortString();
266        }
267        
268        public String getName() {
269                //String name = planet.getName();
270                String name = planet.getTypeNameWithWorld();
271                return "Survey " + name + getPostfixForState();
272        }
273        
274
275        @Override
276        public FactionAPI getFactionForUIColors() {
277                return faction;
278        }
279
280        public String getSmallDescriptionTitle() {
281                return getName();
282        }
283        
284
285        @Override
286        public void createSmallDescription(TooltipMakerAPI info, float width, float height) {
287                Color h = Misc.getHighlightColor();
288                Color g = Misc.getGrayColor();
289                Color tc = Misc.getTextColor();
290                float pad = 3f;
291                float opad = 10f;
292
293                info.addImage(faction.getLogo(), width, 128, opad);
294
295                String name = planet.getName();
296                
297                String authorities = "authorities";
298                if (!faction.getId().equals(market.getFactionId())) {
299                        authorities = "concerns";
300                }
301                
302                info.addPara("%s " + authorities + " " + market.getOnOrAt() + " " + market.getName() + 
303                                " have posted a reward for completing a full survey of " + name + ", " + 
304                                planet.getSpec().getAOrAn() + " " + planet.getTypeNameWithWorld().toLowerCase() + ".",
305                                opad, faction.getBaseUIColor(), Misc.ucFirst(faction.getPersonNamePrefix()));
306                
307                
308                if (isPosted() || isAccepted()) {
309                        addBulletPoints(info, ListInfoMode.IN_DESC);
310                        
311                        info.showFullSurveyReqs(planet, true, opad);
312                        
313//                      SurveyPlugin plugin = (SurveyPlugin) Global.getSettings().getNewPluginInstance("surveyPlugin");
314//                      plugin.init(Global.getSector().getPlayerFleet(), planet);
315//
316//                      
317//                      Map<String, Integer> required = plugin.getRequired();
318//                      Map<String, Integer> consumed = plugin.getConsumed();
319//
320//                      StatBonus stat = new StatBonus();
321//                      int id = 0;
322//                      for (String key : required.keySet()) {
323//                              CommoditySpecAPI com = Global.getSettings().getCommoditySpec(key);
324//                              int qty = required.get(key);
325//                              
326//                              stat.modifyFlat("" + id++, qty, Misc.ucFirst(com.getLowerCaseName()));
327//                      }
328//                      for (String key : consumed.keySet()) {
329//                              CommoditySpecAPI com = Global.getSettings().getCommoditySpec(key);
330//                              int qty = consumed.get(key);
331//                              
332//                              stat.modifyFlat("" + id++, qty, Misc.ucFirst(com.getLowerCaseName()));
333//                      }
334//                      
335//                      info.addPara("The following resources are required for your fleet to run a full survey of " + name + ":", opad);
336//                      info.setLowGridRowHeight();
337//                      info.addStatModGrid(200, 50f, opad, opad, stat, new StatModValueGetter() {
338//                              public String getPercentValue(StatMod mod) { return null; }
339//                              public String getMultValue(StatMod mod) { return null; }
340//                              public Color getModColor(StatMod mod) { return null; }
341//                              public String getFlatValue(StatMod mod) {
342//                                      return "" + (int)mod.value;
343//                              }
344//                      });
345                        
346                        addGenericMissionState(info);
347                        
348                        addAcceptOrAbandonButton(info, width, "Accept", "Abandon");
349                } else {
350                        addGenericMissionState(info);
351                        
352                        addBulletPoints(info, ListInfoMode.IN_DESC);
353                }
354
355        }
356        
357        public String getIcon() {
358                return Global.getSettings().getSpriteName("campaignMissions", "survey_planet");
359        }
360        
361        public Set<String> getIntelTags(SectorMapAPI map) {
362                Set<String> tags = super.getIntelTags(map);
363                tags.add(Tags.INTEL_EXPLORATION);
364                tags.add(Tags.INTEL_MISSIONS);
365                tags.add(faction.getId());
366                return tags;
367        }
368
369        @Override
370        public SectorEntityToken getMapLocation(SectorMapAPI map) {
371                return planet;
372        }
373
374
375        
376}