using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Telerik.Sitefinity.Modules.News;
using Telerik.Sitefinity.News.Model;
using Telerik.Sitefinity.Workflow;

namespace SitefinityWebApp
{
    public class EditContent_ModifyItemByLiveIDNativeAPI
    {
        private void ModifyItemByLiveIDNativeAPI(Guid liveId)
        {
            NewsManager manager = NewsManager.GetManager();
            NewsItem live = manager.GetNewsItems().Where(newsItem => newsItem.Id == liveId).FirstOrDefault();

            if (live != null)
            {
                //Edit the item to get the master version.
                NewsItem master = manager.Lifecycle.Edit(live) as NewsItem;

                //Check out the master to get a temp version.
                NewsItem temp = manager.Lifecycle.CheckOut(master) as NewsItem;

                //Make the modifications to the temp version.
                temp.Title = "New Title";
                temp.LastModified = DateTime.UtcNow;
                temp.Urls.Clear();
                temp.UrlName = Regex.Replace(temp.Title.ToLower(), @"[^\w\-\!\$\'\(\)\=\@\d_]+", "-");

                //Checkin the temp and get the updated master version. 
                //After the check in the temp version is deleted.
                master = manager.Lifecycle.CheckIn(temp) as NewsItem;

                manager.SaveChanges();

                //Publish the news item.
                var bag = new Dictionary<string, string>();
                bag.Add("ContentType", typeof(NewsItem).FullName);
                WorkflowManager.MessageWorkflow(master.Id, typeof(NewsItem), null, "Publish", false, bag);
            }
        }
    }
}