//// GET: api/RemovePage/5
        public HttpResponseMessage Get(string id)
        {

            Logging.LogErrors(ConfigurationValues.ErrorLogPath, "start page removal");

            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
            id = id + ",";
            PDFNet.Initialize("CT Orthopaedic Specialists(ct-ortho.com):ENTCPU:1::W:AMS(20160714):DF4FD2223CBF58B9128E100F400DD2BC2BFD701DC22C3C2E6D83F6B6F5C7");
            PDFDoc newDocument = new PDFDoc();

            string[] pagesToDelete = id.Split(',');
            DocumentRepository documentData = new DocumentRepository();
            int pageCount = 0;
            CurrentDocuments currentDocuments = documentData.GetCurrentDocumentPathPDF(Utility.GetUserName());
            string pathToCurrentPdfFile = currentDocuments.PathToCurrentPDFDocument;
            string pathToCurrentPdfFileTemp = pathToCurrentPdfFile.Replace(".pdf", "temp.pdf");
            string pathToCurrentXodFile = documentData.GetCurrentDocumentPathXOD(Utility.GetUserName());

            PDFDoc removePagesFromDocument = new PDFDoc(pathToCurrentPdfFile);

            pageCount = removePagesFromDocument.GetPageCount();
            if (pageCount > 1)
            {
                try
                {
                    Logging.LogErrors(ConfigurationValues.ErrorLogPath, "begin remove page");
                    PageIterator itr = removePagesFromDocument.GetPageIterator(int.Parse(pagesToDelete[0]));
                    removePagesFromDocument.PageRemove(itr);
                    Logging.LogErrors(ConfigurationValues.ErrorLogPath, "end remove page");
                }
                catch (Exception er)
                {
                    Logging.LogErrors(ConfigurationValues.ErrorLogPath, er.ToString());
                }

                File.Create(pathToCurrentXodFile).Dispose();
                removePagesFromDocument.Save(pathToCurrentPdfFileTemp, 0);
                File.Delete(pathToCurrentXodFile);
                pdftron.Filters.Filter objFilter = pdftron.PDF.Convert.ToXod(pathToCurrentPdfFileTemp);
                System.Threading.Thread.Sleep(ConfigurationValues.XodSaveDelay);
                objFilter.WriteToFile(pathToCurrentXodFile,true );
                documentData.AddUpdateCurrentDocument(Utility.GetUserName(), pathToCurrentXodFile, pathToCurrentPdfFileTemp,
                    currentDocuments.CurrentDocumentList, documentData.GetFullPathToDocument(Utility.GetUserName()));
                Logging.LogErrors(ConfigurationValues.ErrorLogPath, "open stream");
                var stream = new FileStream(pathToCurrentXodFile, FileMode.Open);
                result.Content = new StreamContent(stream);
                result.Content.Headers.ContentType =
                    new MediaTypeHeaderValue("application/octet-stream");
                Logging.LogErrors(ConfigurationValues.ErrorLogPath, ConfigurationValues.XodFileName);
                result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = ConfigurationValues.XodFileName
                };
            }
            Logging.LogErrors(ConfigurationValues.ErrorLogPath, "done");

            return result;
        }
        // GET: api/DeleteDocument
        public IHttpActionResult Get()
        {
            DocumentRepository documentData = new DocumentRepository();
            ArchiveDocument archiveDocument = new ArchiveDocument();

            CurrentDocuments documentsToDelete = documentData.GetCurrentDocumentPathPDF(Utility.GetUserName());

            string[] faxesToDelete = documentsToDelete.CurrentDocumentList.Split('~');

            for (int i = 0; i < faxesToDelete.Length - 1; i++)
            {
                string[] documentName = faxesToDelete[i].Split('\\');
                archiveDocument.ArchiveTheDocument(documentName[documentName.Length - 1],faxesToDelete[i], Utility.GetUserName());

                System.IO.File.Delete(faxesToDelete[i]);
                documentData.DeleteDocumentInFolder(faxesToDelete[i]);
            }
            return Ok();
        }
        // POST: api/Annotations
        public void Post([FromBody]Annotations value)
        {
            DocumentRepository documentData = new DocumentRepository();
            CurrentDocuments currentDocuments = documentData.GetCurrentDocumentPathPDF(Utility.GetUserName());
            string [] pathParts = currentDocuments.PathToCurrentPDFDocument.Split('\\');
            string tempPDFPath = string.Empty;

            for (int i = 0; i < pathParts.Length - 1 ; i++)
            {
                tempPDFPath = tempPDFPath + pathParts[i] + "\\";
            }

            tempPDFPath = tempPDFPath + "temp" + pathParts[pathParts.Length -1];

            System.IO.File.Copy(currentDocuments.PathToCurrentPDFDocument, tempPDFPath,true);
            try
            {

                PDFDoc in_doc = new PDFDoc(tempPDFPath);
                {
                    in_doc.InitSecurityHandler();

                    //string str = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><xfdf xmlns=\"http://ns.adobe.com/xfdf\" xml:space=\"preserve\"><square subject=\"Rectangle\" page=\"0\" name=\"cf4d2e58-e9c5-2a58-5b4d-9b4b1a330e45\" title=\"user\" creationdate=\"D:20120827112326-07'00'\" date=\"D:20120827112326-07'00'\" rect=\"227.7814207650273,597.6174863387978,437.07103825136608,705.0491803278688\" color=\"#000000\" interior-color=\"#FFFF00\" flags=\"print\" width=\"1\"><popup flags=\"print,nozoom,norotate\" open=\"no\" page=\"0\" rect=\"0,792,0,792\" /></square></xfdf>";
                    string str = value.Data;

                    using (FDFDoc fdoc = new FDFDoc(FDFDoc.CreateFromXFDF(str)))
                    {
                        in_doc.FDFMerge(fdoc);
                        in_doc.Save(currentDocuments.PathToCurrentPDFDocument, SDFDoc.SaveOptions.e_linearized);
                    }
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
        }
        // POST: api/SendFax
        public IHttpActionResult Post([FromBody] Fax faxValues)
        {

            Logging.LogErrors(ConfigurationValues.ErrorLogPath, "Start Creating Fax");

            OperationResult createFaxRecordOperationResult = new Models.OperationResult();
            OperationResult sendFaxToMultiTechOperationResult = new Models.OperationResult();

            FaxRepository faxData = new FaxRepository();
            DocumentRepository documentData = new DocumentRepository();

            string[] faxesToSendList = faxValues.FaxTo.Split('~');
            string permanentFaxPath = string.Empty;

            SendFax sendFax = new SendFax();

            try
            {
                for (int i = 0; i < faxesToSendList.Length - 1; i++)
                {

                    Logging.LogErrors(ConfigurationValues.ErrorLogPath, "Getting fax information");

                    FaxingInformation faxingInformatonInitial = new FaxingInformation();

                    faxingInformatonInitial.DocumentList = faxValues.DocumentList;
                    faxingInformatonInitial.FaxTo = faxesToSendList[i];
                    faxingInformatonInitial.Notes = faxValues.Notes;
                    faxingInformatonInitial.From = faxValues.From;
                    faxingInformatonInitial.Cover = faxValues.Cover;
                    faxingInformatonInitial.CoverSheetOnly = faxValues.CoverOnly;

                    Logging.LogErrors(ConfigurationValues.ErrorLogPath, "Getting fax information");                    
                    //Create Fax
                    FaxingInformation faxingInformatonComplete = sendFax.CreateFax(faxingInformatonInitial);

                    System.IO.File.Copy(ConfigurationValues.TemporaryFaxPath
                        + Utility.GetUserName() + "\\" + faxingInformatonComplete.FaxName,
                        ConfigurationValues.PernamentFaxPath
                        + faxingInformatonComplete.FaxName, true);

                    createFaxRecordOperationResult = faxData.SendFax(faxingInformatonComplete, ConfigurationValues.PernamentFaxPath
                        + faxingInformatonComplete.FaxName, faxValues.From, faxValues.Notes);

                    if (createFaxRecordOperationResult.Success)
                    {
                        sendFaxToMultiTechOperationResult = sendFaxMultitech.SendTheFax(faxingInformatonComplete.Name, faxingInformatonComplete.FaxPath,
                            faxValues.From, faxingInformatonComplete.FaxNumber, createFaxRecordOperationResult.MessageList[0], ConfigurationValues.ApplicationPath);
                        if (sendFaxToMultiTechOperationResult.Success)
                        {
                            archiveDocument = new ArchiveDocument();

                            CurrentDocuments faxTodocument = documentData.GetCurrentDocumentPathPDF(Utility.GetUserName());
                            string[] filesToDelete = faxTodocument.CurrentDocumentList.Split('~');
                            for (int j = 0; j < filesToDelete.Length - 1; j++)
                            {
                                //try
                                //{
                                //    File.Delete(ConfigurationValues.OutboundFaxDirectory + "\\" + Utility.GetUserName() + "\\" + filesToDelete[j]);
                                //}
                                //catch { }
                                try
                                {
                                    string[] fileParts = filesToDelete[j].Split('\\');

                                    archiveDocument.ArchiveTheDocument(fileParts[fileParts.Length - 1], filesToDelete[j], Utility.GetUserName());

                                    File.Delete(filesToDelete[j]);
                                }
                                catch { }

                                documentData.DeleteDocumentInFolder(filesToDelete[j]);
                            }

                            System.IO.File.Delete(ConfigurationValues.TemporaryFaxPath
                                + Utility.GetUserName()
                                + "\\" + faxingInformatonComplete.FaxName);
                        }
                        else
                        {
                            faxData.UpdateFaxRecord(createFaxRecordOperationResult.MessageList[0]);
                        }
                    }
                    else
                    {
                        return BadRequest(createFaxRecordOperationResult.ErrorMessage);
                    }
                }
            }
            catch (Exception er)
            {
                return InternalServerError(er);
            }

            CurrentDocuments documentsToDelete = documentData.GetCurrentDocumentPathPDF(Utility.GetUserName());

            try
            {
                File.Delete(documentData.GetFullPathToDocument(Utility.GetUserName()));
            }
            catch { }

            string[] faxesToDelete = documentsToDelete.CurrentDocumentList.Split('~');

            try
            {
                for (int i = 0; i < faxesToDelete.Length - 1; i++)
                {
                    System.IO.File.Delete(ConfigurationValues.OutboundFaxDirectory + "\\"
                        + Utility.GetUserName() + "\\"
                        + faxesToDelete[i]);
                }
            }
            catch { }
            return Ok();
        }
        // GET: api/SeparatePDF/5
        public HttpResponseMessage Get(string id)
        //public string Get(string id)
        {
            id = id + ",";
            PDFNet.Initialize("CT Orthopaedic Specialists(ct-ortho.com):ENTCPU:1::W:AMS(20160714):DF4FD2223CBF58B9128E100F400DD2BC2BFD701DC22C3C2E6D83F6B6F5C7");
            PDFDoc newDocument = new PDFDoc();
            string[] pagesSeparationGroups = id.Split(',');
            string[] newPDFNames = new string[pagesSeparationGroups.Length - 1];
            PDFDoc[] NewPDFDocs = new PDFDoc[pagesSeparationGroups.Length - 1];
            //string pathToCurrentPdfFile = documentData.GetCurrentDocumentPathPDF(Utility.GetUserName());

            for (int i = 0; i < newPDFNames.Length; i++)
            {
                newPDFNames[i] = Guid.NewGuid().ToString() + ".pdf";
                NewPDFDocs[i] = new PDFDoc();
            }

            DocumentRepository documentData = new DocumentRepository();
            //int pageCount = 0;

            CurrentDocuments currentDocuments = documentData.GetCurrentDocumentPathPDF(Utility.GetUserName());
            string pathToCurrentPdfFile = currentDocuments.PathToCurrentPDFDocument;

            //string[] fileName = pathToCurrentPdfFile.Split('\\');

            //File.Move(pathToCurrentPdfFile, ConfigurationValues.TemporaryFaxPath + "\\" + pathToCurrentPdfFile[pathToCurrentPdfFile.Length - 1]);
            PDFDoc separatePagesFromDocument = new PDFDoc(pathToCurrentPdfFile);

            for (int i = 0; i < pagesSeparationGroups.Length - 1; i++)
            {
                string[] pagesSeparation = pagesSeparationGroups[i].Split('-');

                //PageIterator itr = separatePagesFromDocument.GetPageIterator(i);
                NewPDFDocs[i].InsertPages(0, separatePagesFromDocument, int.Parse(pagesSeparation[0]), int.Parse(pagesSeparation[1]), PDFDoc.InsertFlag.e_none);
                NewPDFDocs[i].Save(ConfigurationValues.OutboundFaxDirectory + "\\" + Utility.GetUserName() + "\\" + newPDFNames[i], 0);
            }

            //            string pathToCurrentPdfFileTemp = pathToCurrentPdfFile.Replace(".pdf", "temp.pdf");
            //string pathToCurrentXodFile = documentData.GetCurrentDocumentPathXOD(Utility.GetUserName());
            separatePagesFromDocument.Close();
            separatePagesFromDocument.Dispose();
            File.Delete(pathToCurrentPdfFile);


            for (int i = 0; i < newPDFNames.Length; i++)
            {
                NewPDFDocs[i].Close();
                NewPDFDocs[i].Dispose();
            }

            string[] deleteTheDocumentList = currentDocuments.CurrentDocumentList.Split('~');
            for (int i = 0; i < deleteTheDocumentList.Length - 1; i++)
            {
                File.Delete(ConfigurationValues.OutboundFaxDirectory + "\\" + Utility.GetUserName() + "\\" + deleteTheDocumentList[i]);
            }
           // ConfigurationValues.OutboundFaxDirectory + "\\" + Utility.GetUserName() + "\\"


            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
            return result;
        }
        public FaxingInformation CreateFax(FaxingInformation faxingInformation)
        {
            string newPDF = string.Empty;
            string temporaryPath = string.Empty;

            faxingInformation.FaxName
                = Guid.NewGuid().ToString() + ".pdf";

            FaxRepository faxData = new FaxRepository();
            string[] FirstFaxTo = faxingInformation.FaxTo.Split('~');
            List<FaxToInformation> data = new List<FaxToInformation>();

            if (faxingInformation.FaxTo.Substring(0, 1) == "G")
            {
                data = faxData.GetFaxToInformationGreenway(FirstFaxTo[0]);
            }
            else
            {
                data = faxData.GetFaxToInformation(FirstFaxTo[0]);
            }

            try
            {
                faxingInformation.FaxTo = data[0].Name;

            }
            catch
            {

            }
            try
            {
                //StringCollection listOfPSFiles = new StringCollection();

                DocumentRepository documentData = new DocumentRepository();
                CurrentDocuments faxTodocument = documentData.GetCurrentDocumentPathPDF(Utility.GetUserName());
                Logging.LogErrors(ConfigurationValues.ErrorLogPath, faxTodocument.PathToCurrentPDFDocument);                    
                MemoryStream newPDFStream = Utility.CreateMemoryStreamFromPDF(faxTodocument.PathToCurrentPDFDocument);

                temporaryPath = ConfigurationValues.TemporaryFaxPath + Utility.GetUserName() + "\\"
                    + faxingInformation.FaxName;

                Logging.LogErrors(ConfigurationValues.ErrorLogPath, temporaryPath);                    
                FileStream newPDFStreamFile = new FileStream(temporaryPath, FileMode.Create);

                newPDFStream.WriteTo(newPDFStreamFile);
                Logging.LogErrors(ConfigurationValues.ErrorLogPath, "writing to file");                    
                newPDFStream.Close();
                Logging.LogErrors(ConfigurationValues.ErrorLogPath, "Closing stream");                    
                newPDFStreamFile.Close();

                MemoryStream coverSheet
                    = CreateCoverSheetV2(faxingInformation.FaxTo, data[0].FaxNumber, Utility.GetPDFPageCount(newPDFStreamFile.Name),
                    faxingInformation.Notes, faxingInformation.From, int.Parse(faxingInformation.Cover));

                faxingInformation.PageCount = Utility.GetPDFPageCount(newPDFStreamFile.Name);
                faxingInformation.FaxNumber = UpdatedFaxNumber(data[0].FaxNumber);
                faxingInformation.Name = faxingInformation.FaxTo;

                FileStream presStream = new FileStream(ConfigurationValues.TemporaryFaxPath + Utility.GetUserName()
                    + "\\cover.pdf", FileMode.Create);
                coverSheet.WriteTo(presStream);
                coverSheet.Close();
                presStream.Close();
                if (faxingInformation.CoverSheetOnly == "T")
                {
                    File.Copy(ConfigurationValues.TemporaryFaxPath + Utility.GetUserName()
                            + "\\cover.pdf", newPDFStreamFile.Name, true);
                    File.Delete(ConfigurationValues.TemporaryFaxPath + Utility.GetUserName()
                            + "\\cover.pdf");
                }
                else
                {
                    Utility.MergeTwoPDFDocuments(ConfigurationValues.TemporaryFaxPath + Utility.GetUserName()
                       + "\\cover.pdf", newPDFStreamFile.Name);
                }

                faxingInformation.FaxPath = newPDFStreamFile.Name;

                return faxingInformation;
            }
            catch (Exception er)
            {
                Logging.LogErrors(ConfigurationValues.ErrorLogPath, er.ToString());
                return faxingInformation;
            }
        }