public InspectionOrder ConvertToIO(PolicyXMLResponse policyXML)
        {
            InspectionOrder                newIO              = new InspectionOrder();
            InspectionOrderProperty        newProperty        = new InspectionOrderProperty();
            InspectionOrderPropertyGeneral newPropertyGeneral = new InspectionOrderPropertyGeneral();

            string currentCity  = _cityRepository.RetrieveByName(policyXML.Property.LegalAddress.City, policyXML.Property.LegalAddress.State).Name;
            string currentState = _stateRepository.Retrieve(policyXML.Property.LegalAddress.State).Name;

            string fullAddress = $"{policyXML.Property.LegalAddress.Street1} {currentCity} {currentState} {policyXML.Property.LegalAddress.ZipCode}";

            var insuredName = policyXML.Policy.InsuredName.Split(' ');
            var nameLength  = insuredName.Length;

            var firstName = "";

            for (int i = 0; i < nameLength - 1; i++)
            {
                firstName = firstName + " " + insuredName[i];
            }
            var lastName = insuredName[nameLength - 1];

            //Policy
            Policy newPolicy = new Policy
            {
                PolicyNumber               = policyXML.Policy.PolicyNumber,
                InsuredFirstName           = firstName,
                InsuredLastName            = lastName,
                CoverageA                  = policyXML.Policy.Coverage,
                InceptionDate              = DateTime.Parse(policyXML.Policy.EffectiveDate),
                InsuredState               = currentState,
                InsuredZipCode             = policyXML.Property.LegalAddress.ZipCode,
                InsuredCity                = currentCity,
                Address                    = fullAddress,
                InsuredEmail               = AppSettings.Configuration["InsuredEmail"],
                WildfireAssessmentRequired = false,
                AgencyName                 = policyXML.Agent.Name,
                AgencyPhoneNumber          = policyXML.Agent.Phone.PhoneNumber,
                PropertyValueId            = PropertyValue(policyXML.Policy.Coverage),
                InspectionStatusId         = "PA"
            };

            var completePolicy = _mapService.GetAddressGeocode(newPolicy);

            newPolicy = completePolicy;

            //Property
            newPropertyGeneral.StreetAddress1 = policyXML.Property.LegalAddress.Street1;
            newPropertyGeneral.StreetAddress2 = "";
            newPropertyGeneral.StateId        = policyXML.Property.LegalAddress.State;
            newPropertyGeneral.ZipCode        = policyXML.Property.LegalAddress.ZipCode;
            newPropertyGeneral.CityId         = _cityRepository.RetrieveByName(policyXML.Property.LegalAddress.City, policyXML.Property.LegalAddress.State).Id;

            //Inspection Order
            newIO.CreatedDate     = DateTime.Now.Date;
            newIO.LastUpdatedDate = DateTime.Now.Date;

            var userId = GetUser("underwriter_user");

            newIO.CreatedById = new Guid(userId.Result);

            newIO.Policy           = newPolicy;
            newIO.Property         = newProperty;
            newIO.Property.General = newPropertyGeneral;

            return(newIO);
        }
        public Image InsertOrUpdateNonWildfireAssessmentMitigationRecommendation(InspectionOrder ioFromClient)
        {
            var existingIo = Context.Set <InspectionOrder>()
                             .Include(x => x.Property)
                             .ThenInclude(x => x.NonWildfireAssessment)
                             .ThenInclude(x => x.Mitigation)
                             .ThenInclude(x => x.Recommendations)
                             .SingleOrDefault(x => x.Id.Equals(ioFromClient.Id));

            if (existingIo == null)
            {
                throw new Exception("Inspection Order not found.");
            }

            var property = existingIo.Property;

            if (property == null)
            {
                property = new InspectionOrderProperty {
                    Id = ioFromClient.Id
                };
                context.Entry(property).State = EntityState.Added;
            }

            var nonWildfireAssessment = property.NonWildfireAssessment;

            if (nonWildfireAssessment == null)
            {
                nonWildfireAssessment = new InspectionOrderPropertyNonWildfireAssessment {
                    Id = ioFromClient.Id
                };
                context.Entry(nonWildfireAssessment).State = EntityState.Added;
            }

            var mitigation = nonWildfireAssessment.Mitigation;

            if (mitigation == null)
            {
                mitigation = new InspectionOrderPropertyNonWildfireAssessmentMitigation {
                    Id = ioFromClient.Id
                };
                context.Entry(mitigation).State = EntityState.Added;
            }

            if (mitigation.Recommendations == null)
            {
                mitigation.Recommendations = new List <InspectionOrderPropertyNonWildfireAssessmentMitigationRecommendations>();
            }

            var pmFromClient = ioFromClient.Property.NonWildfireAssessment.Mitigation.Recommendations.First();

            pmFromClient.InspectionOrderPropertyNonWildfireId = mitigation.Id;

            var requirementsDbSet = context.Set <InspectionOrderPropertyNonWildfireAssessmentMitigationRecommendations>();

            var imageFromClient = pmFromClient.Image;

            var isAdd = (imageFromClient.Id == Guid.Empty);
            var newId = Guid.NewGuid();

            if (isAdd)
            {
                imageFromClient.Id = newId;
                _imageService.UpdateImageFile(imageFromClient, newId);

                pmFromClient.Image = imageFromClient;
                requirementsDbSet.Add(pmFromClient);

                context.SaveChanges();

                return(pmFromClient.Image);
            }
            else // update
            {
                var existingPm = requirementsDbSet.SingleOrDefault(
                    w => w.InspectionOrderPropertyNonWildfireId == pmFromClient.InspectionOrderPropertyNonWildfireId &&
                    w.ImageId == imageFromClient.Id);

                if (existingPm == null)
                {
                    throw new Exception("Image not found.");
                }

                context.Entry(existingPm).CurrentValues.SetValues(pmFromClient);

                // this means that the image file from the client has changed
                if (imageFromClient.File != null)
                {
                    _imageService.UpdateImageFile(imageFromClient, newId);

                    var existingImage = _imageRepository.Retrieve(existingPm.ImageId);

                    context.Entry(existingImage).CurrentValues.SetValues(imageFromClient);

                    try
                    {
                        context.SaveChanges();

                        _imageService.DeleteImageFileInDisk(existingPm.Image.FilePath);
                        _imageService.DeleteImageFileInDisk(existingPm.Image.ThumbnailPath);

                        return(existingPm.Image);
                    }
                    catch (Exception e)
                    {
                    }
                }
                else
                {
                    context.SaveChanges();
                }


                return(imageFromClient);
            }
        }