using System;
using Telerik.Sitefinity.DynamicModules;
using Telerik.Sitefinity.DynamicModules.Model;
using Telerik.Sitefinity.GeoLocations.Model;
using Telerik.Sitefinity.Lifecycle;
using Telerik.Sitefinity.Model;
using Telerik.Sitefinity.Utilities.TypeConverters;

namespace SitefinityWebApp
{
    public class AddressFieldEdit
    {
        public void ModifyAddressField(Guid itemId)
        {
            DynamicModuleManager dynamicModuleManager = DynamicModuleManager.GetManager();
            Type sightseeingType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.Tourism.Sightseeing");

            DynamicContent item = dynamicModuleManager.GetDataItem(sightseeingType, itemId);

            // Then we check it out
            DynamicContent checkOutSightseeingItem = dynamicModuleManager.Lifecycle.CheckOut(item) as DynamicContent;

            var address = checkOutSightseeingItem.GetValue<Address>("Location");

            address.Street = "Hooper Ave";
            // We can now change any values of the item
            checkOutSightseeingItem.SetValue("Location", address);

            // Now we need to check in, so the changes apply
            ILifecycleDataItem checkInSightseeingItem = dynamicModuleManager.Lifecycle.CheckIn(checkOutSightseeingItem);

            //Finnaly we publish the item again
            dynamicModuleManager.Lifecycle.Publish(checkInSightseeingItem);

            // You need to call SaveChanges() in order for the items to be actually persisted to data store
            dynamicModuleManager.SaveChanges();

        }
    }
}