public override bool RequirementMet(ConfiguredContract contract)
 {
     int level = (int)Math.Round(ScenarioUpgradeableFacilities.GetFacilityLevel(facility) *
         ScenarioUpgradeableFacilities.GetFacilityLevelCount(facility)) + 1;
     return level == 0 && contract != null && contract.ContractState == Contracts.Contract.State.Active ||
         level >= minLevel && level <= maxLevel;
 }
        public override void OnLoad(ConfigNode node)
        {
            try
            {
                foreach (ConfigNode child in node.GetNodes("CONTRACT"))
                {
                    ConfiguredContract contract = null;
                    try
                    {
                        contract = new ConfiguredContract();
                        Contract.Load(contract, child);
                    }
                    catch (Exception e)
                    {
                        LoggingUtil.LogWarning(this, "Ignored an exception while trying to load a pre-loaded contract:");
                        LoggingUtil.LogException(e);
                    }

                    if (contract != null && contract.contractType != null)
                    {
                        contract.preLoaded = true;
                        contracts.Add(contract);
                    }
                }
            }
            catch (Exception e)
            {
                LoggingUtil.LogError(this, "Error loading ContractPreLoader from persistance file!");
                LoggingUtil.LogException(e);
                ExceptionLogWindow.DisplayFatalException(ExceptionLogWindow.ExceptionSituation.SCENARIO_MODULE_LOAD, e, "ContractPreLoader");
            }
        }
        /// <summary>
        /// Copy constructor.
        /// </summary>
        public WaypointGenerator(WaypointGenerator orig, ConfiguredContract contract)
            : base()
        {
            foreach (WaypointData old in orig.waypoints)
            {
                // Copy waypoint data
                for (int i = 0; i < old.count; i++)
                {
                    WaypointData wpData = new WaypointData(old, contract);
                    waypoints.Add(wpData);

                    // Set the name
                    if (old.names.Any())
                    {
                        wpData.waypoint.name = (old.names.Count() == 1 ? old.names.First() : old.names.ElementAtOrDefault(i));
                    }
                    if (string.IsNullOrEmpty(wpData.waypoint.name) || wpData.waypoint.name.ToLower() == "site")
                    {
                        wpData.waypoint.name = StringUtilities.GenerateSiteName(random.Next(), wpData.waypoint.celestialBody, !wpData.waterAllowed);
                    }
                }
            }
            initialized = orig.initialized;
            orig.initialized = false;
            this.contract = contract;

            Initialize();
        }
        public override bool RequirementMet(ConfiguredContract contract)
        {
            // Perform another validation of the target body to catch late validation issues due to expressions
            if (!ValidateTargetBody())
            {
                return false;
            }

            // Validate the CelestialBodySubtree exists
            CelestialBodySubtree cbProgress = GetCelestialBodySubtree();
            if (cbProgress == null)
            {
                LoggingUtil.LogError(this, ": ProgressNode for targetBody " + targetBody.bodyName + " not found.");
                return false;
            }

            if (checkType == CheckType.MANNED)
            {
                return cbProgress.IsReached && cbProgress.IsCompleteManned;
            }
            else if (checkType == CheckType.UNMANNED)
            {
                return cbProgress.IsReached && cbProgress.IsCompleteUnmanned;
            }

            return true;
        }
        public override bool RequirementMet(ConfiguredContract contract)
        {
            foreach (string tech in techs)
            {
                ProtoTechNode techNode = ResearchAndDevelopment.Instance.GetTechState(tech);
                if (techNode == null || techNode.state != RDTech.State.Available)
                {
                    return false;
                }
            }

            foreach (string partModule in partModules)
            {
                bool hasModule = false;
                foreach (AvailablePart part in PartLoader.LoadedPartsList)
                {
                    if (part.partPrefab == null || part.partPrefab.Modules == null)
                    {
                        continue;
                    }

                    if (ResearchAndDevelopment.PartTechAvailable(part))
                    {
                        hasModule = true;
                        break;
                    }
                }

                if (!hasModule)
                {
                    return false;
                }
            }

            foreach (string partModuleType in partModuleTypes)
            {
                bool hasType = false;
                foreach (AvailablePart part in PartLoader.LoadedPartsList)
                {
                    if (part.partPrefab == null || part.partPrefab.Modules == null)
                    {
                        continue;
                    }

                    if (part.partPrefab.HasValidContractObjective(partModuleType) && ResearchAndDevelopment.PartTechAvailable(part))
                    {
                        hasType = true;
                        break;
                    }
                }

                if (!hasType)
                {
                    return false;
                }
            }

            return true;
        }
        public override bool RequirementMet(ConfiguredContract contract)
        {
            // Late validation
            partModuleType.All(Validation.ValidatePartModuleType);

            // Actual check
            return partModuleType.All(s => ProgressUtilities.HaveModuleTypeTech(s));
        }
 public override bool RequirementMet(ConfiguredContract contract)
 {
     foreach (AvailablePart part in parts)
     {
         if (!ResearchAndDevelopment.PartModelPurchased(part))
         {
             return false;
         }
     }
     return true;
 }
        public override bool RequirementMet(ConfiguredContract contract)
        {
            // Perform another validation of the target body to catch late validation issues due to expressions
            if (!ValidateTargetBody())
            {
                return false;
            }

            double coverageInPercentage = SCANsatUtil.GetCoverage(SCANsatUtil.GetSCANtype(scanType), targetBody);
            return coverageInPercentage >= minCoverage && coverageInPercentage <= maxCoverage;
        }
 public override bool RequirementMet(ConfiguredContract contract)
 {
     foreach (string tech in techs)
     {
         ProtoTechNode techNode = ResearchAndDevelopment.Instance.GetTechState(tech);
         if (techNode == null || techNode.state != RDTech.State.Available)
         {
             return false;
         }
     }
     return true;
 }
 public override bool RequirementMet(ConfiguredContract contract)
 {
     bool requirementMet = true;
     foreach (ContractRequirement requirement in childNodes)
     {
         if (requirement.enabled)
         {
             requirementMet &= requirement.CheckRequirement(contract);
         }
     }
     return requirementMet;
 }
        public override bool RequirementMet(ConfiguredContract contract)
        {
            LoggingUtil.LogVerbose(this, "Checking requirement");

            // Perform another validation of the target body to catch late validation issues due to expressions
            if (!ValidateTargetBody())
            {
                return false;
            }

            return RemoteTechProgressTracker.Instance.ActiveRange(targetBody) > range;
        }
        public bool GenerateContract(ConfiguredContract contract)
        {
            LoggingUtil.LogVerbose(this, "Request to generate contract of prestige level " + contract.Prestige);
            ConfiguredContract templateContract = GetNextContract(contract.Prestige, HighLogic.LoadedScene == GameScenes.FLIGHT);

            if (templateContract == null)
            {
                return false;
            }

            // Copy the contract details
            contract.CopyFrom(templateContract);
            return true;
        }
        public override bool RequirementMet(ConfiguredContract contract)
        {
            // Perform another validation of the target body to catch late validation issues due to expressions
            if (!ValidateTargetBody())
            {
                return false;
            }

            if (ResourceScenario.Instance == null)
            {
                return false;
            }

            return ResourceScenario.Instance.gameSettings.GetPlanetScanInfo().Where(psd => psd.PlanetId == targetBody.flightGlobalsIndex).Any();
        }
        public override bool RequirementMet(ConfiguredContract contract)
        {
            // Cache the tech tree
            if (techTree == null)
            {
                ConfigNode techTreeRoot = ConfigNode.Load(HighLogic.CurrentGame.Parameters.Career.TechTreeUrl);
                if (techTreeRoot != null)
                {
                    techTree = techTreeRoot.GetNode("TechTree");
                }

                if (techTreeRoot == null || techTree == null)
                {
                    LoggingUtil.LogError(this, "Couldn't load tech tree from " + HighLogic.CurrentGame.Parameters.Career.TechTreeUrl);
                    return false;
                }
            }

            foreach (string tech in techs)
            {
                ConfigNode techNode = techTree.GetNodes("RDNode").Where(n => n.GetValue("id") == tech).FirstOrDefault();

                if (techNode == null)
                {
                    LoggingUtil.LogWarning(this, "No tech node found with id '" + tech + "'");
                    return false;
                }

                // Get the state of the parents, as well as the anyToUnlock flag
                bool anyToUnlock = ConfigNodeUtil.ParseValue<bool>(techNode, "anyToUnlock");
                IEnumerable<bool> parentsUnlocked = techNode.GetNodes("Parent").
                    Select(n => ResearchAndDevelopment.Instance.GetTechState(n.GetValue("parentID"))).
                    Select(p => p != null && p.state == RDTech.State.Available);

                // Check if the parents have met the unlock criteria
                if (anyToUnlock && parentsUnlocked.Any(unlocked => unlocked) ||
                    !anyToUnlock && parentsUnlocked.All(unlocked => unlocked))
                {
                    continue;
                }
                else
                {
                    return false;
                }
            }

            return true;
        }
        public override ContractBehaviour Generate(ConfiguredContract contract)
        {
            // Set legacy values
            if (legacy)
            {
                kerbals = passengerName.Select(name => new Kerbal(gender, name, experienceTrait)).ToList();
            }

            // Set the kerbal type
            foreach (Kerbal kerbal in kerbals)
            {
                kerbal.kerbalType = kerbalType;
            }

            return new SpawnPassengers(kerbals, count);
        }
        /// <summary>
        /// Loads a behaviour from a ConfigNode.
        /// </summary>
        /// <param name="configNode"></param>
        /// <param name="contract"></param>
        /// <returns></returns>
        public static ContractBehaviour LoadBehaviour(ConfigNode configNode, ConfiguredContract contract)
        {
            // Determine the type
            string typeName = configNode.GetValue("type");
            Type type = ContractConfigurator.GetAllTypes<ContractBehaviour>().Where(t => t.FullName == typeName).FirstOrDefault();
            if (type == null)
            {
                throw new Exception("No ContractBehaviour with type = '" + typeName + "'.");
            }

            // Instantiate and load
            ContractBehaviour behaviour = (ContractBehaviour)Activator.CreateInstance(type);
            behaviour.contract = contract;
            behaviour.Load(configNode);
            return behaviour;
        }
        public override bool RequirementMet(ConfiguredContract contract)
        {
            IEnumerable<ProtoCrewMember> crew = HighLogic.CurrentGame.CrewRoster.Crew;

            // Filter by trait
            if (trait != null)
            {
                crew = crew.Where<ProtoCrewMember>(cm => cm.experienceTrait.TypeName == trait);
            }

            // Filter by experience
            crew = crew.Where<ProtoCrewMember>(cm => cm.experienceLevel >= minExperience && cm.experienceLevel <= maxExperience);

            // Check counts
            int count = crew.Count();
            return count >= minCount && count <= maxCount;
        }
        public override bool RequirementMet(ConfiguredContract contract)
        {
            // Perform another validation of the target body to catch late validation issues due to expressions
            if (!ValidateTargetBody())
            {
                return false;
            }

            // Validate the CelestialBodySubtree exists
            CelestialBodySubtree cbProgress = GetCelestialBodySubtree();
            if (cbProgress == null)
            {
                LoggingUtil.LogError(this.GetType(), ": ProgressNode for targetBody " + targetBody.bodyName + " not found.");
                return false;
            }
            return true;
        }
        public override bool RequirementMet(ConfiguredContract contract)
        {
            int metCount = 0;
            foreach (ContractRequirement requirement in childNodes)
            {
                if (requirement.enabled)
                {
                    if (requirement.CheckRequirement(contract))
                    {
                        metCount++;
                    }

                }
            }

            return metCount >= count;
        }
        public override bool RequirementMet(ConfiguredContract contract)
        {
            // Perform another validation of the target body to catch late validation issues due to expressions
            if (!ValidateTargetBody())
            {
                return false;
            }

            if (pqsCity != null)
            {
                latitude = targetBody.GetLatitude(pqsCity.transform.position);
                longitude = targetBody.GetLongitude(pqsCity.transform.position);
                pqsCity = null;
            }

            return SCANsatUtil.IsCovered(latitude, longitude, SCANsatUtil.GetSCANtype(scanType), targetBody);
        }
        /// <summary>
        /// Copy constructor.
        /// </summary>
        public WaypointGenerator(WaypointGenerator orig, ConfiguredContract contract)
            : base()
        {
            foreach (WaypointData old in orig.waypoints)
            {
                // Copy waypoint data
                for (int i = 0; i < old.count; i++)
                {
                    waypoints.Add(new WaypointData(old, contract));
                }
            }
            initialized = orig.initialized;
            orig.initialized = false;
            this.contract = contract;

            Initialize();
        }
        /// <summary>
        /// Generates all the ContractBehaviour objects required for the array of ConfigNodes, and
        /// adds them to the host object.
        /// </summary>
        /// <param name="contract">Contract to generate behaviours for</param>
        /// <param name="behaviourNodes">The behaviour factories to use</param>
        /// <return>Whether generation was successful or not</return>
        public static bool GenerateBehaviours(ConfiguredContract contract, List<BehaviourFactory> behaviourNodes)
        {
            foreach (BehaviourFactory behaviourFactory in behaviourNodes)
            {
                if (behaviourFactory.enabled)
                {
                    ContractBehaviour behaviour = behaviourFactory.Generate(contract);
                    if (behaviour == null)
                    {
                        throw new Exception(behaviourFactory.GetType().FullName + ".Generate() returned a null ContractBehaviour!");
                    }

                    // Add ContractBehaviour to the host
                    contract.AddBehaviour(behaviour);
                }
            }

            return true;
        }
        public override bool RequirementMet(ConfiguredContract contract)
        {
            LoggingUtil.LogVerbose(this, "Checking requirement");

            // Perform another validation of the target body to catch late validation issues due to expressions
            if (!ValidateTargetBody())
            {
                return false;
            }

            if (RemoteTechProgressTracker.Instance == null)
            {
                // Assume no coverage
                return maxCoverage == 0.0;
            }

            double coverage = RemoteTechProgressTracker.GetCoverage(targetBody);
            return coverage >= minCoverage && coverage <= maxCoverage;
        }
        public override bool RequirementMet(ConfiguredContract contract)
        {
            IEnumerable<UpgradeableFacility> facilities = UnityEngine.Object.FindObjectsOfType<UpgradeableFacility>().
                Where<UpgradeableFacility>(f => f.name == facility);

            if (facilities.Count() > 0)
            {
                UpgradeableFacility upgradeableFacility = facilities.First<UpgradeableFacility>();

                int level = upgradeableFacility.FacilityLevel;
                return level >= minLevel && level <= maxLevel;
            }
            else
            {
                // Should only get here if the facility name entered was bad
                LoggingUtil.LogError(this, "Coudn't read find facility with name '" + facility + "'!");
                return false;
            }
        }
        public override void OnLoad(ConfigNode node)
        {
            try
            {
                foreach (ConfigNode child in node.GetNodes("CONTRACT"))
                {
                    ConfiguredContract contract = new ConfiguredContract();
                    Contract.Load(contract, child);

                    contractDetails[contract.Prestige].contracts.Enqueue(contract);
                }
            }
            catch (Exception e)
            {
                LoggingUtil.LogError(this, "Error loading ContractPreLoader from persistance file!");
                LoggingUtil.LogException(e);
                ExceptionLogWindow.DisplayFatalException(ExceptionLogWindow.ExceptionSituation.SCENARIO_MODULE_LOAD, e, "ContractPreLoader");
            }
        }
        public override bool RequirementMet(ConfiguredContract contract)
        {
            foreach (string partModuleType in partModuleTypes)
            {
                foreach (AvailablePart part in PartLoader.LoadedPartsList)
                {
                    if (part.partPrefab == null || part.partPrefab.Modules == null)
                    {
                        continue;
                    }

                    if (part.partPrefab.HasValidContractObjective(partModuleType) && ResearchAndDevelopment.PartTechAvailable(part) && ResearchAndDevelopment.PartModelPurchased(part))
                    {
                        return true;
                    }
                }
            }

            return false;
        }
        public override bool RequirementMet(ConfiguredContract contract)
        {
            foreach (string partModule in partModules)
            {

                // Search for a part that has our module
                bool found = false;
                foreach (AvailablePart p in PartLoader.Instance.loadedParts)
                {
                    if (p != null && p.partPrefab != null && p.partPrefab.Modules != null)
                    {
                        foreach (PartModule pm in p.partPrefab.Modules)
                        {
                            if (pm != null && pm.moduleName != null && pm.moduleName == partModule)
                            {
                                found = true;
                                break;
                            }
                        }
                    }

                    if (found)
                    {
                        if (ResearchAndDevelopment.PartModelPurchased(p))
                        {
                            break;
                        }
                        else
                        {
                            found = false;
                        }
                    }
                }

                if (!found)
                {
                    return false;
                }
            }
            return true;
        }
        public override bool RequirementMet(ConfiguredContract contract)
        {
            // Get the count of finished contracts
            int finished = 0;
            double lastFinished = 0.0;

            // Finished contracts - Contract Configurator style
            if (ccType != null)
            {
                IEnumerable<ConfiguredContract> completedContract = ContractSystem.Instance.GetCompletedContracts<ConfiguredContract>().
                    Where(c => c.contractType != null && c.contractType.name.Equals(ccType));
                finished = completedContract.Count();
                if (finished > 0)
                {
                    // TODO - this isn't working out
                    lastFinished = completedContract.OrderByDescending<ConfiguredContract, double>(c => c.DateFinished).First().DateFinished;
                }
            }
            // Finished contracts - stock style
            else
            {
                // Call the GetCompletedContracts with our type, and get the count
                Contract[] completedContract = (Contract[])typeof(ContractSystem).GetMethod("GetCompletedContracts").MakeGenericMethod(contractClass).Invoke(ContractSystem.Instance, null);
                finished = completedContract.Count();
                if (finished > 0)
                {
                    lastFinished = completedContract.OrderByDescending<Contract, double>(c => c.DateFinished).First().DateFinished;
                }
            }

            // Check cooldown
            if (cooldownDuration.Value > 0.0 && finished > 0 && lastFinished + cooldownDuration.Value > Planetarium.GetUniversalTime())
            {
                LoggingUtil.LogDebug(this, "Returning false due to cooldown for " + contractType.name);
                return false;
            }

            // Return based on the min/max counts configured
            return (finished >= minCount) && (finished <= maxCount);
        }
        public override bool RequirementMet(ConfiguredContract contract)
        {
            // Get the count of accepted contracts
            int accepted = 0;

            // Finished contracts - Contract Configurator style
            if (ccType != null)
            {
                IEnumerable<ConfiguredContract> acceptedContract = ContractSystem.Instance.Contracts.Select(c => c as ConfiguredContract).
                    Where(c => c != null && c.contractType != null && c.contractType.name.Equals(ccType) && c.ContractState == Contract.State.Active);
                accepted = acceptedContract.Count();
            }
            // Finished contracts - stock style
            else
            {
                // Call the GetCompletedContracts with our type, and get the count
                IEnumerable<Contract> acceptedContract = ContractSystem.Instance.Contracts.Where(c => c != null && c.GetType() == contractClass &&
                    c.ContractState == Contract.State.Active);
                accepted = acceptedContract.Count();
            }

            // Return based on the min/max counts configured
            return (accepted >= minCount) && (accepted <= maxCount);
        }
 public override ContractBehaviour Generate(ConfiguredContract contract)
 {
     return new DialogBox(details);
 }