//***************************************************************************
//
//    Copyright (c) 2006/2007 Iggy Mwangi. All rights reserved.
//    Contact me at iggy.mw@gmail.com with questions, suggestions
//    This code is provided "AS IS" without warranty of any kind.
//***************************************************************************
using System;
using System.Windows.Forms;
using Microsoft.VisualStudio.Tools.Applications.Runtime;
using Outlook = Microsoft.Office.Interop.Outlook;
using Office = Microsoft.Office.Core;
using Word = Microsoft.Office.Interop.Word;
using System.Text.RegularExpressions;


namespace BlogThisOutlookAddin
{
    public partial class ThisApplication
    {
        // User interface elements.
        Outlook.Explorer _currentExplorer = null;
        Office.CommandBar _blogThisToolBar;
        Office.CommandBarButton _blogThisButton;
        Office.CommandBarButton _rssStatsButton;
        Outlook.Explorers _selectExplorers;
        Outlook.PostItem _rssItem   ; // the selected item


        /// <summary>
        /// Called when the add-in is loaded by Outlook.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ThisApplication_Startup(object sender, System.EventArgs e)
        {
            _currentExplorer = this.ActiveExplorer();
            _currentExplorer.SelectionChange += new Outlook
                .ExplorerEvents_10_SelectionChangeEventHandler
                (CurrentExplorer_Event);

            _selectExplorers = this.Explorers;
            _selectExplorers.NewExplorer += new Outlook
                .ExplorersEvents_NewExplorerEventHandler(newExplorer_Event);
            AddToolbar();

        }

        private void ThisApplication_Shutdown(object sender, System.EventArgs e)
        {
        }

        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisApplication_Startup);
            this.Shutdown += new System.EventHandler(ThisApplication_Shutdown);
        }

        #endregion

        # region CurrentExplorer_Event handler
        private void CurrentExplorer_Event()
        {
            _blogThisButton.Enabled = true;
            Outlook.MAPIFolder selectedFolder =
                this.ActiveExplorer().CurrentFolder;
            String expMessage = "Your current folder is "
                + selectedFolder.Name + ".\n";
            String itemMessage = "Item is unknown.";
            try
            {
                if (this.ActiveExplorer().Selection.Count > 0)
                {
                    Object selObject = this.ActiveExplorer().Selection[1];
                    if (selObject is Outlook.PostItem)
                    {
                        Outlook.PostItem postItem =
                            (selObject as Outlook.PostItem);
                        itemMessage = "The item subject is " + postItem.Subject;
                        // mailItem.Display(false);
                        _rssItem = postItem;
                       // MessageBox.Show(mailItem.Body);
                    }
                    else _blogThisButton.Enabled = false;

                }
                expMessage = expMessage + itemMessage;
            }
            catch (Exception ex)
            {
                expMessage = ex.Message;
            }
            // MessageBox.Show(expMessage);
        }

        # endregion

        #region
        private void newExplorer_Event(Outlook.Explorer new_Explorer)
        {
            ((Outlook._Explorer)new_Explorer).Activate();
            _blogThisToolBar = null;
            AddToolbar();
        }
        #endregion

        #region add the toolbar
        private void AddToolbar()
        {

            if (_blogThisToolBar == null)
            {
                Office.CommandBars cmdBars =
                    this.ActiveExplorer().CommandBars;
                _blogThisToolBar = cmdBars.Add("BlogThis ToolBar",
                    Office.MsoBarPosition.msoBarTop, false, true);
            }
            try
            {
                Office.CommandBarButton button_1 =
                    (Office.CommandBarButton)_blogThisToolBar.Controls
                    .Add(1, missing, missing, missing, missing);
                button_1.Style = Office
                    .MsoButtonStyle.msoButtonCaption;
                button_1.Caption = "Blog This!";
                button_1.Tag = "_blogThisButton";
                button_1.Style = Microsoft.Office.Core.MsoButtonStyle.
                msoButtonIconAndCaption;
                button_1.FaceId = 162;
                button_1.Enabled = false;
                if (this._blogThisButton == null)
                {
                    this._blogThisButton = button_1;
                    _blogThisButton.Click += new Office.
                        _CommandBarButtonEvents_ClickEventHandler
                        (ButtonClickBlogThis);
                }

                Office.CommandBarButton button_2 = (Office
                  .CommandBarButton)_blogThisToolBar.Controls.Add
                  (1, missing, missing, missing, missing);
                button_2.Style = Office
                    .MsoButtonStyle.msoButtonCaption;
                button_2.Caption = "RSS Stats";
                button_2.Tag = "_rssStatsButton";
                button_2.Style = Microsoft.Office.Core.MsoButtonStyle.
                msoButtonIconAndCaption;
                button_2.FaceId = 107;
                button_2.Enabled = true;
                _blogThisToolBar.Visible = true;
                if (this._rssStatsButton == null)
                {
                    this._rssStatsButton = button_2;
                    _rssStatsButton.Click += new Office.
                        _CommandBarButtonEvents_ClickEventHandler
                        (ButtonClickRSSStats);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region event handlers for the buttons
        private void ButtonClickRSSStats(Office.CommandBarButton ctrl,
               ref bool cancel)
        {
          GetRssStats();
        }


        private void ButtonClickBlogThis(Office.CommandBarButton ctrl,
                ref bool cancel)
        {
            object oMissing = System.Reflection.Missing.Value;

            //Start Word and create a new document.
            Word._Application oWord;
            Word._Document oDoc;
            oWord = new Word.Application();
            oWord.Visible = true;

            // using the blogTemplate custom template
           object oTemplate = "blogTemplate.docx";
            oDoc = oWord.Documents.Add(ref oTemplate, ref oMissing,
               ref oMissing, ref oMissing);

            //Insert a paragraph at the beginning of the document.
            Word.Paragraph inAnArticlePhrase;
            inAnArticlePhrase = oDoc.Content.Paragraphs.Add(ref oMissing);
            inAnArticlePhrase.Range.Text = GetPostHeader();

            //Insert a paragraph for the footer.
            Word.Paragraph footerPhrase;
            footerPhrase = oDoc.Content.Paragraphs.Add(ref oMissing);
            footerPhrase.Range.Text = GetPostItemFooter();
            footerPhrase.Range.Font.Bold = 1;


        }

        private string GetPostHeader()
        {
            string content = _rssItem.SenderName + " , in an article titled "
                   + _rssItem.Subject + "  ..........\n  " + GetPostItemBody();
            return content;
        }

        private string GetPostItemBody()
        {
            string content = _rssItem.Body.Replace("HYPERLINK", " ");
            content = content.Replace("View article...", " ");
            return content;

        }
        private string GetPostItemFooter()
        {
            string content = " from "  +  _rssItem.Subject +  " by " + _rssItem.
            SenderName
                + " published on  " + _rssItem.SentOn;
            return content;

        }
        #endregion

        #region
        private void GetRssStats()
        {
            // Find an existing folder.
            Outlook.NameSpace mapiNamespace = this.GetNamespace("MAPI");
            Outlook.MAPIFolder inboxFolder = mapiNamespace.GetDefaultFolder(
            Outlook.OlDefaultFolders.olFolderInbox);
            Outlook.MAPIFolder targetFolder = null;
            Outlook.MAPIFolder rootFolder = inboxFolder.Parent as Outlook.
            MAPIFolder;
            if (rootFolder != null)
            {
                foreach (Outlook.MAPIFolder folder in rootFolder.Folders)
                {
                    //the name of the folder to Find
                    if (folder.Name.Equals("RSS Feeds"))
                    {

                        targetFolder = folder;
                        string caption = "Subscriptions" ;
                        string msg = "Subscribed to " + targetFolder.Folders.
                        Count + " feeds. ";
                        MessageBox.Show(msg, caption, MessageBoxButtons.OK);
                        ;
                        break;
                    }
                }
            }
        }
        #endregion

    }
}
//code reading guidlines:
//based on conventions from http://iggybill.blogspot.com/2006/04/coding-
guidelines.html
//
//For this code file
// 1. Prefix private member variables with _underscore".
// 2. I Always place an open curly brack ({) on a new line.", unless ... see
guidlines
// 3. I use #regions to break down the code into related sections,
// 4. My single goal in using conventions is to make it easy to read the code ..
etc
// 5. If this code file is not readable, email me at iggy.mw@gmail.com