using BS.Shared;
using Microsoft.Office.Interop.Word;
using System.IO;
using Application = Microsoft.Office.Interop.Word.Application;

namespace BeWo.Office
{
    internal class WordListener
    {
        private Application wordApp;
        private Document wordDoc;
        private ViewDestination viewDestination;

        public WordListener(Application wordApp, Document wordDoc, ViewDestination destination)
        {
            this.wordApp = wordApp;
            this.wordDoc = wordDoc;
            viewDestination = destination;
        }

        void wordApp_DocumentBeforeSave(Document doc, ref bool saveAsUI, ref bool cancel)
        {
            if (this.viewDestination == ViewDestination.Edit && Path.Combine(doc.Path, doc.Name).ToLower() == Path.Combine(this.wordDoc.Path, this.wordDoc.Name).ToLower())
            {
                doc.MailMerge.MainDocumentType = WdMailMergeMainDocType.wdNotAMergeDocument;
            }
        }

        private void Dispose()
        {
            wordApp = null;
            wordDoc = null;
            
            OfficeManager.DeleteTempFiles();
        }
    }
}
