using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Diagnostics;
using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint.Publishing.WebControls;
using System.Globalization;

namespace jeremythake.tvshowschedulesite
{
    public class ScheduleListEventReceiver : SPItemEventReceiver
    {
        public override void ItemAdded(SPItemEventProperties properties)
        {
            SPListItem currentListItem = properties.ListItem;
            string scheduleTttle = currentListItem["Title"].ToString();
            string scheduleName = string.Format("{0}-s{1}e{2}", scheduleTttle, currentListItem["Season_x0020_Number"].ToString(), currentListItem["Episode_x0020_Number"].ToString());
            string scheduleListTemplateName = "Schedule";
            string listName = "Schedule";
            string itemStyle = "ScheduleStyle";

            using (SPWeb web = properties.OpenWeb())
            {
                PublishingWeb pw = PublishingWeb.GetPublishingWeb(web);

                //Get List Template - used below
                SPListTemplateCollection listTemplates = web.Site.RootWeb.ListTemplates;
                SPListTemplate scheduleListTemplate = listTemplates[scheduleListTemplateName];

                // Create the new page in the PublishingWeb.
                PublishingPageCollection pages = pw.GetPublishingPages();
                PageLayout[] pageLayouts = pw.GetAvailablePageLayouts();
                PageLayout blankWebPartPageLayout = null;
                foreach (PageLayout pageLayout in pageLayouts)
                    if (pageLayout.Title == "Blank Web Part Page")
                        blankWebPartPageLayout = pageLayout;
                PublishingPage newPage = pages.Add(scheduleName + ".aspx", blankWebPartPageLayout);
                string checkInComment = "Page created";
                //Title modified here
                newPage.ListItem["Title"] = scheduleName;
                newPage.ListItem.Update();
                newPage.CheckIn(checkInComment);

                SPFile categoryPageFile = web.GetFile("Pages/" + scheduleName + ".aspx");
                if (categoryPageFile.Exists)
                {
                    categoryPageFile.CheckOut();
                    using (SPLimitedWebPartManager webPartManager = categoryPageFile.GetLimitedWebPartManager(PersonalizationScope.Shared))
                    {
                        ContentByQueryWebPart contentByQueryWebPart = new ContentByQueryWebPart();
                        contentByQueryWebPart.Title = "Related Schedules";
                        contentByQueryWebPart.WebUrl = web.Url;
                        contentByQueryWebPart.BaseType = string.Empty;
                        contentByQueryWebPart.ServerTemplate = Convert.ToString((int)scheduleListTemplate.Type, CultureInfo.InvariantCulture);
                        contentByQueryWebPart.CommonViewFields = "Air_x0020_Date,AirDate;Episode_x0020_Number,Episode;Season_x0020_Number,Season";
                        contentByQueryWebPart.ItemStyle = itemStyle;
                        //contentByQueryWebPart.ItemXslLink = site.Url + "/Style%20Library/jeremythake/schedule.xsl";
                        //TODO: filter by schedule
                        contentByQueryWebPart.FilterField1 = web.Lists[listName].Fields["Title"].Id.ToString("B");
                        contentByQueryWebPart.Filter1ChainingOperator = ContentByQueryWebPart.FilterChainingOperator.Or;
                        contentByQueryWebPart.FilterOperator1 = ContentByQueryWebPart.FilterFieldQueryOperator.Contains;
                        contentByQueryWebPart.Filter2ChainingOperator = ContentByQueryWebPart.FilterChainingOperator.And;
                        contentByQueryWebPart.FilterValue1 = scheduleTttle;
                        contentByQueryWebPart.FilterType1 = "Text";
                        contentByQueryWebPart.ShowUntargetedItems = false;
                        webPartManager.AddWebPart(contentByQueryWebPart, "Right", 0);
                    }
                    categoryPageFile.CheckIn("Added Page");
                    categoryPageFile.Publish("Published");
                }
            }
        }
    }
}

