//public OperationResult SendFax(MiscFaxInformation miscFaxInformation, string permanentFaxPath, string from, string notes)
        public OperationResult SendFax( FaxingInformation miscFaxInformation, string permanentFaxPath, string from, string notes)
        {

            OperationResult operationResult = new Models.OperationResult();

            string now = DateTime.Now.ToShortDateString()
                + " "
                + DateTime.Now.ToShortTimeString();

            using (IDbConnection db = new SqlConnection(ConfigurationValues.WaldenFaxConnection))
            {
                try
                {
                    const string query = "INSERT INTO [FaxesSendServer]("
                        + "[AccountID]"
                        + ",[UserID]"
                        + ",[FaxName]"
                        + ",[FaxPath]"
                        + ",[FaxNumber]"
                        + ",[RecipientName]"
                        + ",[Notes]"
                        + ",[PageCount]"
                        + ",[FaxSent]"
                        + ",[InUse]"
                        + ",[ToTif]"
                        + ",[CallWait]"
                        + ",[TimesCalled]"
                        + ",[Status]"
                        + ",[ShowFax]"
                        + ",[CreateTime]"
                        + ",[CompletionTime]"
                        + ",[DateStamp])"
                        + " VALUES("
                        + "@AccountID"
                        + ",@UserID"
                        + ",@FaxName"
                        + ",@FaxPath"
                        + ",@FaxNumber"
                        + ",@RecipientName"
                        + ",@Notes"
                        + ",@PageCount"
                        + ",@FaxSent"
                        + ",@InUse"
                        + ",@ToTif"
                        + ",@CallWait"
                        + ",@TimesCalled"
                        + ",@Status"
                        + ",@ShowFax"
                        + ",@CreateTime"
                        + ",@CompletionTime"
                        + ",@DateStamp)";

                    int rowsAffectd = db.Execute(query, new
                    {
                        @AccountID = 1001,
                        @UserID = Utility.GetUserName(),
                        @FaxName = miscFaxInformation.Name,
                        @FaxPath = permanentFaxPath,
                        @FaxNumber = miscFaxInformation.FaxNumber,
                        @RecipientName = from,
                        @Notes = notes,
                        @PageCount = miscFaxInformation.PageCount,
                        @FaxSent = "Y",
                        @InUse = "N",
                        @ToTif = "Y",
                        @CallWait = 0,
                        @TimesCalled = 0,
                        @Status = "New Fax Entry",
                        @ShowFax = "Y",
                        @CreateTime = now,
                        @CompletionTime = string.Empty,
                        @DateStamp = now
                    });

                    int sendFaxId = GetSendFaxID();
                    int r = 5;
                    operationResult.Success = true;
                    operationResult.AddMessage(sendFaxId.ToString());

                    return operationResult;
                }
                catch (Exception er)
                {
                    operationResult.Success = false;
                    operationResult.AddMessage(er.ToString());
                    return operationResult;
                }
            }
        }
        //public MiscFaxInformation CreateFax(string faxDocumentList, string _faxTo, string notes,
         //   string from, string cover)
        public FaxingInformation CreateFax(FaxingInformation faxingInformation)
        {
            //MiscFaxInformation miscFaxInformation = new MiscFaxInformation();

            string newPDF = string.Empty;
            string temporaryPath = string.Empty;

            faxingInformation.NameFromDateTimeString
                = Utility.GetFileNameFromDateTimeString() + ".pdf";

            //var repository = new WaldenCompleteFaxWeb.Repository.FaxToInformation();
            var repository = new FaxToInformation();

            FaxData faxData = new FaxData();
            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();

                string[] words = faxingInformation.DocumentList.Split('~');

                for (int i = 0; i < words.Length; i++)
                {
                    if (words[i].Length > 0)
                    {
                        listOfPSFiles.Add(words[i]);
                    }
                }

                MemoryStream newPDFStream = CreatePreviewFax(listOfPSFiles);

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

                FileStream newPDFStreamFile = new FileStream(temporaryPath, FileMode.Create);

                newPDFStream.WriteTo(newPDFStreamFile);
                newPDFStream.Close();
                newPDFStreamFile.Close();

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


                //miscFaxInformation.PageCount = Walden.Medical.Library.Pdf.GetPDFPageCount(_newPDFStreamFile.Name);
                //miscFaxInformation.FaxNumber =  UpdatedFaxNumber(data[0].FaxNumber);
                //miscFaxInformation.Name = faxTo;

                faxingInformation.PageCount = Walden.Medical.Library.Pdf.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
                {
                    Walden.Medical.Library.Pdf.MergeTwoDocuments(ConfigurationValues.TemporaryFaxPath + Utility.GetUserName()
                        + "\\cover.pdf", newPDFStreamFile.Name);
                }

                faxingInformation.FaxPath = newPDFStreamFile.Name;
                //miscFaxInformation.FaxPath = _newPDFStreamFile.Name;

                return faxingInformation;
            }
            catch (Exception er)
            {
                return faxingInformation;
            }
        }
        // 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();
        }
        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;
            }
        }