void SetupDefaultColors()
 {
     SetupDefaultColor(DefaultCreatureColorIds.Unknown, Color.Empty);
     SetupDefaultColor(DefaultCreatureColorIds.Black, Color.DarkSlateGray);
     SetupDefaultColor(DefaultCreatureColorIds.White, Color.GhostWhite);
     SetupDefaultColor(DefaultCreatureColorIds.Grey, Color.LightGray);
     SetupDefaultColor(DefaultCreatureColorIds.Brown, Color.Brown);
     SetupDefaultColor(DefaultCreatureColorIds.Gold, Color.Gold);
     SetupDefaultColor(DefaultCreatureColorIds.BloodBay, Color.RosyBrown);
     SetupDefaultColor(DefaultCreatureColorIds.EbonyBlack, Color.Black);
     SetupDefaultColor(DefaultCreatureColorIds.PiebaldPinto, Color.DarkGray);
     grangerContext.SubmitChanges();
 }
        private void buttonOK_Click(object sender, EventArgs e)
        {
            if (!ValidateCreatureIdentity())
            {
                this.DialogResult = System.Windows.Forms.DialogResult.None;
            }
            else
            {
                try
                {
                    if (OpMode == CreatureViewEditOpType.New)
                    {
                        var newEntity = new CreatureEntity()
                        {
                            Id = CreatureEntity.GenerateNewCreatureId(context)
                        };
                        creature = new Creature(mainForm, newEntity, context, creatureColorDefinitions);
                    }

                    List <CreatureTrait> traitlist = new List <CreatureTrait>();
                    foreach (var item in checkedListBoxTraits.CheckedItems)
                    {
                        try
                        {
                            traitlist.Add(CreatureTrait.FromWurmTextRepr(item.ToString()));
                        }
                        catch (Exception _e)
                        {
                            logger.Error(_e, "failed to create creature trait from text:" + item.ToString());
                        }
                    }
                    var traitlistArray = traitlist.ToArray();

                    creature.Name          = textBoxName.Text.Trim();
                    creature.Father        = comboBoxFather.Text.Trim();
                    creature.Mother        = comboBoxMother.Text.Trim();
                    creature.TakenCareOfBy = textBoxCaredForBy.Text.Trim();
                    creature.BrandedFor    = textBoxBrandedFor.Text.Trim();

                    creature.Traits = traitlistArray;

                    creature.TraitsInspectSkill = (float)numericUpDownAHskill.Value;
                    float traitSkill = CreatureTrait.GetMinSkillForTraits(traitlistArray, checkBoxEpic.Checked);
                    if (creature.TraitsInspectSkill < traitSkill)
                    {
                        creature.TraitsInspectSkill = traitSkill;
                    }
                    creature.EpicCurve = checkBoxEpic.Checked;

                    creature.Comments = textBoxComment.Text;
                    creature.IsMale   = radioButtonMale.Checked;
                    creature.Color    = creatureColorDefinitions.GetForId(comboBoxColor.Text);
                    creature.Age      = CreatureAge.CreateAgeFromEnumString(comboBoxAge.Text);

                    creature.NotInMoodUntil = dateTimePickerBred.Value;
                    creature.GroomedOn      = dateTimePickerGroomed.Value;
                    creature.PregnantUntil  = dateTimePickerPregnant.Value;
                    creature.BirthDate      = dateTimePickerBirthDate.Value;

                    creature.SetTag("diseased", checkBoxDiseased.Checked);
                    creature.SetTag("dead", checkBoxDead.Checked);
                    creature.SetTag("sold", checkBoxSold.Checked);

                    creature.ServerName = comboBoxServerName.Text.Trim();

                    if (OpMode == CreatureViewEditOpType.New)
                    {
                        creature.Herd = herdId;
                        context.InsertCreature(creature.Entity);
                    }
                    else
                    {
                        context.SubmitChanges();
                    }
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                }
                catch (Exception _e)
                {
                    logger.Error(_e, "problem while updating database, op: " + OpMode);
                    MessageBox.Show("There was a problem on submitting to database.\r\n" + _e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    this.DialogResult = System.Windows.Forms.DialogResult.None;
                }
            }
        }
        bool TryUpdateExistingCreature(CreatureEntity[] herdsFinds)
        {
            if (herdsFinds.Length == 1)
            {
                CreatureEntity oldCreature = herdsFinds[0];

                bool sanityFail = false;

                #region SANITY_CHECKS

                string sanityFailReason = null;

                // Verifying if creature parents match.

                // Wurm trivia:
                // If a creature has a mother name or a father name, these names cannot change.
                // However when parent dies, Wurm loses reference and the name is no longer in the log event!

                // father checks
                if (String.IsNullOrEmpty(oldCreature.FatherName) &&
                    !String.IsNullOrEmpty(creatureBuffer.FatherName))
                {
                    sanityFail = true;
                    if (sanityFailReason == null)
                    {
                        sanityFailReason = "Old father was blank but new data has a father name";
                    }
                }

                if (!String.IsNullOrEmpty(oldCreature.FatherName) &&
                    !String.IsNullOrEmpty(creatureBuffer.FatherName) &&
                    oldCreature.FatherName != creatureBuffer.FatherName)
                {
                    sanityFail = true;
                    if (sanityFailReason == null)
                    {
                        sanityFailReason = "Old data father name was different than new father name";
                    }
                }

                // mother checks
                if (String.IsNullOrEmpty(oldCreature.MotherName) &&
                    !String.IsNullOrEmpty(creatureBuffer.MotherName))
                {
                    sanityFail = true;
                    if (sanityFailReason == null)
                    {
                        sanityFailReason = "Old mother was blank but new data has a mother name";
                    }
                }

                if (!String.IsNullOrEmpty(oldCreature.MotherName) &&
                    !String.IsNullOrEmpty(creatureBuffer.MotherName) &&
                    oldCreature.MotherName != creatureBuffer.MotherName)
                {
                    sanityFail = true;
                    if (sanityFailReason == null)
                    {
                        sanityFailReason = "Old data mother name was different than new mother name";
                    }
                }

                // Verifying if creature traits match.

                // Have to take into account current AH level of the player,
                // as well as the level this creature has been previously inspected at.

                if (oldCreature.TraitsInspectedAtSkill.HasValue)
                {
                    // Skip this check if creature had genesis cast within last 1 hour.
                    // Genesis clears some negative traits.
                    debugLogger.Log(string.Format("Checking creature for Genesis cast (creature name: {0}",
                                                  creatureBuffer.Name));
                    if (!parentModule.Settings.HasGenesisCast(creatureBuffer.Name))
                    {
                        debugLogger.Log("No genesis cast found");
                        var             lowskill      = Math.Min(oldCreature.TraitsInspectedAtSkill.Value, creatureBuffer.InspectSkill);
                        CreatureTrait[] certainTraits = CreatureTrait.GetTraitsUpToSkillLevel(lowskill,
                                                                                              oldCreature.EpicCurve ?? false);
                        var oldCreatureTraits = oldCreature.Traits.ToArray();
                        var newCreatureTraits = creatureBuffer.Traits.ToArray();
                        foreach (var trait in certainTraits)
                        {
                            if (oldCreatureTraits.Contains(trait) != newCreatureTraits.Contains(trait))
                            {
                                sanityFail = true;
                                if (sanityFailReason == null)
                                {
                                    sanityFailReason = "Trait mismatch below inspect skill treshhold (" +
                                                       lowskill + "): " + trait.ToCompactString();
                                }
                                break;
                            }
                        }
                    }
                    else
                    {
                        debugLogger.Log("Genesis cast found, skipping trait sanity check");
                        parentModule.Settings.RemoveGenesisCast(creatureBuffer.Name);
                        debugLogger.Log(string.Format("Removed cached genesis cast data for {0}",
                                                      creatureBuffer.Name));
                    }
                }

                #endregion

                if (sanityFail)
                {
                    debugLogger.Log("sanity check failed for creature update: " + oldCreature + ". Reason: " +
                                    sanityFailReason);
                    trayPopups.Schedule("There was data mismatch when trying to update creature, reason: " + sanityFailReason,
                                        "ERROR AT UPDATE CREATURE",
                                        8000);
                }
                else
                {
                    oldCreature.Age           = creatureBuffer.Age;
                    oldCreature.TakenCareOfBy = creatureBuffer.CaredBy;
                    oldCreature.BrandedFor    = creatureBuffer.BrandedBy;
                    if (creatureBuffer.HasFatherName)
                    {
                        oldCreature.FatherName = creatureBuffer.FatherName;
                    }
                    if (creatureBuffer.HasMotherName)
                    {
                        oldCreature.MotherName = creatureBuffer.MotherName;
                    }
                    oldCreature.ServerName = creatureBuffer.Server.ServerName.Original;
                    if (oldCreature.TraitsInspectedAtSkill <= creatureBuffer.InspectSkill ||
                        creatureBuffer.InspectSkill >
                        CreatureTrait.GetFullTraitVisibilityCap(oldCreature.EpicCurve ?? false))
                    {
                        oldCreature.Traits = creatureBuffer.Traits;
                        oldCreature.TraitsInspectedAtSkill = creatureBuffer.InspectSkill;
                    }
                    else
                    {
                        debugLogger.Log("old creature data had more accurate trait info, skipping");
                    }
                    oldCreature.SetTag("dead", false);
                    oldCreature.SetSecondaryInfoTag(creatureBuffer.SecondaryInfo);
                    oldCreature.IsMale        = creatureBuffer.IsMale;
                    oldCreature.PregnantUntil = creatureBuffer.PregnantUntil;
                    if (oldCreature.Name != creatureBuffer.Name)
                    {
                        if (NameIsUniqueInHerd(creatureBuffer.Name, oldCreature.Herd))
                        {
                            trayPopups.Schedule(String.Format("Updating name of creature {0} to {1}",
                                                              oldCreature.Name,
                                                              creatureBuffer.Name), "CREATURE NAME UPDATE");
                            oldCreature.Name = creatureBuffer.Name;
                        }
                        else
                        {
                            trayPopups.Schedule(String.Format("Could not update name of creature {0} to {1}, " +
                                                              "because herd already has a creature with such name.",
                                                              oldCreature.Name,
                                                              creatureBuffer.Name), "WARNING");
                        }
                    }
                    oldCreature.SmilexamineLastDate = DateTime.Now;
                    if (creatureBuffer.HasColorWurmLogText && grangerSettings.UpdateCreatureColorOnSmilexamines)
                    {
                        oldCreature.CreatureColorId =
                            creatureColorDefinitions.GetColorIdByWurmLogText(creatureBuffer.ColorWurmLogText);
                    }
                    context.SubmitChanges();
                    debugLogger.Log("successfully updated creature in db");
                    trayPopups.Schedule(String.Format("Updated creature: {0}", oldCreature), "CREATURE UPDATED");
                }

                debugLogger.Log("processor buffer cleared");
                return(true);
            }
            return(false);
        }
        void HandleAgeAndTagsUpdates(LogEntry line)
        {
            if (CreatureUpdateAnyEvent && MaybeCreatureAgeLine(line.Content))
            {
                CreatureData data = GetCreatureDataFromAnyLogEvent(line.Content, searchEntireDb: false);

                bool cont = true;

                if (data != null && data.TooManyCreaturesFound)
                {
                    var partialMessage = "selected herds";
                    ScheduleTrayPopup(
                        String.Format(
                            "There are multiple creatures named {0} in {1}, can't update health/age!",
                            data.Creature.Name,
                            partialMessage),
                        "CREATURE UPDATE PROBLEM",
                        5000);
                    cont = false;
                }
                else if (data == null && SearchEntireDb)
                {
                    data = GetCreatureDataFromAnyLogEvent(line.Content, searchEntireDb: true);
                    if (data != null && data.TooManyCreaturesFound)
                    {
                        var partialMessage = "database";
                        ScheduleTrayPopup(
                            String.Format(
                                "There are multiple creatures named {0} in {1}, can't update health/age!",
                                data.Creature.Name,
                                partialMessage),
                            "CREATURE UPDATE PROBLEM",
                            5000);
                        cont = false;
                    }
                }

                if (data != null && cont)
                {
                    if (data.SecondaryInfo != null)
                    {
                        string notify = null;
                        if (data.SecondaryInfo == String.Empty)
                        {
                            if (data.Creature.CheckTag("diseased") ||
                                data.Creature.CheckTag("starving") ||
                                data.Creature.CheckTag("fat"))
                            {
                                notify = "cleared";
                            }
                            data.Creature.SetSecondaryInfoTag(CreatureEntity.SecondaryInfoTag.None);
                        }
                        else if (data.SecondaryInfo == "diseased")
                        {
                            if (!data.Creature.CheckTag("diseased"))
                            {
                                notify = "diseased";
                            }
                            data.Creature.SetSecondaryInfoTag(CreatureEntity.SecondaryInfoTag.Diseased);
                        }
                        else if (data.SecondaryInfo == "starving")
                        {
                            if (!data.Creature.CheckTag("starving"))
                            {
                                notify = "starving";
                            }
                            data.Creature.SetSecondaryInfoTag(CreatureEntity.SecondaryInfoTag.Starving);
                        }
                        else if (data.SecondaryInfo == "fat")
                        {
                            if (!data.Creature.CheckTag("fat"))
                            {
                                notify = "fat";
                            }
                            data.Creature.SetSecondaryInfoTag(CreatureEntity.SecondaryInfoTag.Fat);
                        }


                        bool ageChanged = data.Age != data.Creature.Age;

                        if (notify != null || ageChanged)
                        {
                            string health = null;
                            if (notify != null)
                            {
                                if (notify == "cleared")
                                {
                                    health = "Cleared health tags.";
                                }
                                else
                                {
                                    health = "Set health tag to " + notify + ".";
                                }
                            }

                            string age = null;
                            if (ageChanged)
                            {
                                age = "updated age to " + data.Age;
                            }

                            ScheduleTrayPopup(data.Creature + ": " + health + " " + age, "HEALTH/AGE UPDATE");
                        }

                        data.Creature.Age = data.Age;
                    }
                    context.SubmitChanges();
                }
            }
        }