// GET: api/DeleteDocument
        public IHttpActionResult Get()
        {
            DocumentRepository documentData = new DocumentRepository();
            ArchiveDocument archiveDocument = new ArchiveDocument();
            FolderRepository folderRepository = new FolderRepository();
            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('\\');
                Logging.LogErrors(ConfigurationValues.ErrorLogPath, "Begin Archive");
                archiveDocument.ArchiveTheDocument(documentName[documentName.Length - 1],faxesToDelete[i], Utility.GetUserName());
                Logging.LogErrors(ConfigurationValues.ErrorLogPath, "End Archive");

                try
                {
                    System.IO.File.Delete(faxesToDelete[i]);
                    folderRepository.DeleteFileInFolder(faxesToDelete[i]);
                }
                catch (Exception er)
                {
                    Logging.LogErrors(ConfigurationValues.ErrorLogPath, er.ToString());
                    return BadRequest(er.ToString());
                }

                try
                {
                    documentData.DeleteDocumentInFolder(faxesToDelete[i]);
                }
                catch (Exception er)
                {
                    Logging.LogErrors(ConfigurationValues.ErrorLogPath, er.ToString());
                    return BadRequest(er.ToString());
                }
            }
            return Ok();
        }
        public void SendFileToAnotherUser(FaxFolders sendFileToAnotherUser)
        {
            //1.  Move the file to the new folder
            //2   Insert record giving folder that and name of document

            CurrentDocument currentdocument = new CurrentDocument();
            DocumentRepository documentRepository = new DocumentRepository();
            ArchiveDocument archiveDocument = new ArchiveDocument();

            try {

                using (IDbConnection db = new SqlConnection(ConfigurationValues.PostOfficeDatabaseConnection))
                {

                    string query = "SELECT [ID],[ActiveDirectoryUser],[CurrentDocumentPathXOD],[CurrentDocumentPathPDF]"
                        + " ,[PathToDocument],[CurrentAnnotation],[CurrentListOfDocuments]"
                        + " FROM [CurrentDocument]"
                        + " where [ActiveDirectoryUser] = @ActiveDirectoryUser";

                    currentdocument = db.Query<CurrentDocument>(query, new { @ActiveDirectoryUser = Utility.GetUserName() }).Single();

                    string[] filestoDelete = currentdocument.CurrentListOfDocuments.Split('~');
                    for (int i = 0; i < filestoDelete.Length - 1; i++)
                    {
                        string[] currentDocumentName = filestoDelete[i].Split('\\');
                        Logging.LogErrors(ConfigurationValues.ErrorLogPath, "The document name is: " + currentDocumentName[currentDocumentName.Length - 1]);
                        
                        archiveDocument.ArchiveTheDocument(currentDocumentName[currentDocumentName.Length - 1], filestoDelete[i], Utility.GetUserName());

                        File.Copy(filestoDelete[i], ConfigurationValues.InboundFaxRoot +  sendFileToAnotherUser.NewPath + "\\" + currentDocumentName[currentDocumentName.Length - 1]);

                        try
                        {
                            documentRepository.DeleteDocumentThatIsInAInFolder(filestoDelete[i], Utility.GetUserName());
                            try
                            {
                                File.Delete(filestoDelete[i]);
                            }
                            catch { }
                        }
                        catch (Exception er)
                        {
                            Logging.LogErrors(ConfigurationValues.ErrorLogPath, er.ToString());
                        }
                    }
                }
            }
            catch (Exception er)
            {
                Logging.LogErrors(ConfigurationValues.ErrorLogPath, er.ToString());
            }
        }
        private static void ProcessBarcodedDocuments(ImportDocument newDocumentToImport)
        {
            PostOffice.Api.DataAccess.DocumentRepository documentData = new PostOffice.Api.DataAccess.DocumentRepository();
            CurrentDocuments currentDocument = documentData.GetCurrentDocumentPathPdf(Utility.GetUserName());
            newDocumentToImport.FullPath = currentDocument.PathToCurrentPdfDocument;

            try
            {
                System.IO.FileStream inFile;
                byte[] binaryData;

                try
                {
                    inFile = new System.IO.FileStream(newDocumentToImport.FullPath,
                                              System.IO.FileMode.Open,
                                              System.IO.FileAccess.Read);
                    binaryData = new Byte[inFile.Length];
                    inFile.Read(binaryData, 0,
                                         (int)inFile.Length);
                    inFile.Close();
                }
                catch (Exception er)
                {
                    Logging.LogErrors(ConfigurationValues.ErrorLogPath, er.ToString());
                    string[] fileNameArray = newDocumentToImport.FullPath.Split('\\');
                    string fileName = fileNameArray[fileNameArray.Length - 1];
                    File.Copy(newDocumentToImport.FullPath, pathToErrorFolder + fileName, true);
                    return;
                }

                string base64String;
                try
                {
                    base64String =
                      System.Convert.ToBase64String(binaryData,
                                             0,
                                             binaryData.Length);
                }
                catch (System.ArgumentNullException)
                {
                    //LogErrors("Binary data array is null.");
                    string[] fileNameArray = newDocumentToImport.FullPath.Split('\\');
                    string fileName = fileNameArray[fileNameArray.Length - 1];
                    File.Copy(newDocumentToImport.FullPath, pathToErrorFolder + fileName, true);
                    //AddErrorDocument(pathToErrorFolder + fileName, barCodeText.User);
                    return;
                }

                ContractBuilder oBuilder = new ContractBuilder();
                Greenway.PrimeSuite.DataContracts.Document.DocumentImportChartRequest oRequest = new Greenway.PrimeSuite.DataContracts.Document.DocumentImportChartRequest();

                oRequest.Header = new Greenway.PrimeSuite.DataContracts.API.Header();

                oRequest = oBuilder.BuildDocumentImportChartRequest(base64String);

                oRequest.PrimeSuitePatientId = newDocumentToImport.PatientID;
                oRequest.DocumentTypeID = newDocumentToImport.DocTypeId;

                oRequest.DocumentName = "Lab Result -";
                oRequest.DocumentDescription = string.Empty;
                oRequest.Credentials.PrimeSuiteCredential.PrimeSuiteUserName = greenwayUserID;
                oRequest.Credentials.PrimeSuiteCredential.PrimeSuiteUserPassword = greenwayUserPassword;

                PostOffice.Api.Document ocall = new PostOffice.Api.Document();

                ocall.SendPdf(oRequest, greenwayServer);

                ArchiveDocument archiveDocument = new ArchiveDocument();

                string[] listOfDocumentsToArchive = currentDocument.CurrentDocumentList.Split('~');

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

                return;
            }
            catch (Exception er)
            {
                Logging.LogErrors(ConfigurationValues.ErrorLogPath, er.ToString());
                string[] fileNameArray = newDocumentToImport.FullPath.Split('\\');
                string fileName = fileNameArray[fileNameArray.Length - 1];
                File.Copy(newDocumentToImport.FullPath, pathToErrorFolder + fileName, true);
                return;
            }
        }
        // POST: api/SendFax
        public IHttpActionResult Post([FromBody] Fax faxValues)
        {
            System.IO.Directory.CreateDirectory(ConfigurationValues.TemporaryFaxPath
                        + Utility.GetUserName());

            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('~');

            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)
                        {
                            if (faxValues.SendToEmr == "F")
                            {
                                ArchiveDocument = new ArchiveDocument();

                                CurrentDocuments faxTodocument = documentData.GetCurrentDocumentPathPdf(Utility.GetUserName());
                                string[] filesToDelete = faxTodocument.CurrentDocumentList.Split('~');
                                for (int j = 0; j < filesToDelete.Length - 1; j++)
                                {
                                    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]);
                                }


                                Logging.LogErrors(ConfigurationValues.ErrorLogPath, "Begin Delete file");

                                File.Delete(faxingInformatonComplete.FaxPath);

                                File.Delete(ConfigurationValues.TemporaryFaxPath
                                    + Utility.GetUserName()
                                    + "\\cover.pdf");
                                Logging.LogErrors(ConfigurationValues.ErrorLogPath, "end delete file");

                            }
                        }
                        else
                        {
                            faxData.UpdateFaxRecord(sendFaxToMultiTechOperationResult.MessageList[0]);
                            return BadRequest(sendFaxToMultiTechOperationResult.MessageList[0]);
                        }
                    }
                    else
                    {
                        return BadRequest(createFaxRecordOperationResult.MessageList[0]);
                    }
                }
            }
            catch (Exception er)
            {
                return BadRequest(er.ToString());
            }

            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();
        }
        private static OperationResult ProcessBarcodedDocuments(ImportDocument newDocumentToImport)
        {

            OperationResult operationResult = new OperationResult();

            Logging.LogErrors(ConfigurationValues.ErrorLogPath, "Start Import");
            PostOffice.Api.DataAccess.DocumentRepository documentData = new PostOffice.Api.DataAccess.DocumentRepository();
            CurrentDocuments currentDocument = documentData.GetCurrentDocumentPathPdf(Utility.GetUserName());
            newDocumentToImport.FullPath = currentDocument.PathToCurrentPdfDocument;

            Logging.LogErrors(ConfigurationValues.ErrorLogPath, "Start Creating Base 64");
            try
            {
                System.IO.FileStream inFile;
                byte[] binaryData;

                try
                {
                    inFile = new System.IO.FileStream(newDocumentToImport.FullPath,
                                              System.IO.FileMode.Open,
                                              System.IO.FileAccess.Read);
                    binaryData = new Byte[inFile.Length];
                    inFile.Read(binaryData, 0,
                                         (int)inFile.Length);
                    inFile.Close();
                }
                catch (Exception er)
                {
                    Logging.LogErrors(ConfigurationValues.ErrorLogPath, er.ToString());
                    string[] fileNameArray = newDocumentToImport.FullPath.Split('\\');
                    string fileName = fileNameArray[fileNameArray.Length - 1];
                    File.Copy(newDocumentToImport.FullPath, pathToErrorFolder + fileName, true);
                    operationResult.Success = false;
                    operationResult.AddMessage(er.ToString());
                    return operationResult;
                }

                string base64String;
                try
                {
                    base64String =
                      System.Convert.ToBase64String(binaryData,
                                             0,
                                             binaryData.Length);
                }
                catch (System.ArgumentNullException er)
                {
                    //LogErrors("Binary data array is null.");
                    string[] fileNameArray = newDocumentToImport.FullPath.Split('\\');
                    string fileName = fileNameArray[fileNameArray.Length - 1];
                    File.Copy(newDocumentToImport.FullPath, pathToErrorFolder + fileName, true);
                    operationResult.Success = false;
                    operationResult.AddMessage(er.ToString());
                    return operationResult;
                }

                Logging.LogErrors(ConfigurationValues.ErrorLogPath, "End Base 64");

                ContractBuilder oBuilder = new ContractBuilder();
                Logging.LogErrors(ConfigurationValues.ErrorLogPath, "1");
                Greenway.PrimeSuite.DataContracts.Document.DocumentImportChartRequest oRequest = new Greenway.PrimeSuite.DataContracts.Document.DocumentImportChartRequest();
                oRequest.Header = new Greenway.PrimeSuite.DataContracts.API.Header();
                oRequest = oBuilder.BuildDocumentImportChartRequest(base64String);

                oRequest.PrimeSuitePatientId = newDocumentToImport.PatientID;
                oRequest.DocumentTypeID = newDocumentToImport.DocTypeId;
                oRequest.DocumentName = newDocumentToImport.DocumentName;
                oRequest.DocumentDescription = newDocumentToImport.DocumentName + " " + newDocumentToImport.Initials;
                oRequest.DocumentSignerID = int.Parse(ConfigurationValues.ProviderSignerID);
                Logging.LogErrors(ConfigurationValues.ErrorLogPath, "3");
                if (newDocumentToImport.ProviderId.Length > 0)
                {
                    oRequest.DocumentStatus = Greenway.PrimeSuite.DataContracts.Document.DocumentImportDocumentStatusDocumentImportDocumentStatusEnum.InProgress;
                    oRequest.DocumentSignerID = int.Parse(newDocumentToImport.ProviderId);
                }
                oRequest.Credentials.PrimeSuiteCredential.PrimeSuiteUserName = greenwayUserID;
                oRequest.Credentials.PrimeSuiteCredential.PrimeSuiteUserPassword = greenwayUserPassword;

                PostOffice.Api.Document ocall = new PostOffice.Api.Document();

                ocall.SendPdf(oRequest, greenwayServer);
                ArchiveDocument archiveDocument = new ArchiveDocument();

                string[] listOfDocumentsToArchive = currentDocument.CurrentDocumentList.Split('~');
                for (int i = 0; i < listOfDocumentsToArchive.Length - 1; i++)
                {
                    try
                    {
                        string[] documentName = listOfDocumentsToArchive[i].Split('\\');
                        archiveDocument.ArchiveTheDocument(documentName[documentName.Length - 1], listOfDocumentsToArchive[i], Utility.GetUserName());
                        File.Delete(listOfDocumentsToArchive[i]);
                    }
                    catch (Exception er)
                    {
                        Logging.LogErrors(ConfigurationValues.ErrorLogPath, er.ToString());
                        operationResult.Success = true;
                        operationResult.AddMessage("None");
                        return operationResult;
                    }
                }

                operationResult.Success = true;
                operationResult.AddMessage("None");
                return operationResult;
            }
            catch (Exception er)
            {
                Logging.LogErrors(ConfigurationValues.ErrorLogPath, er.ToString());
                string[] fileNameArray = newDocumentToImport.FullPath.Split('\\');
                string fileName = fileNameArray[fileNameArray.Length - 1];
                File.Copy(newDocumentToImport.FullPath, pathToErrorFolder + fileName, true);
                operationResult.Success = false;
                operationResult.AddMessage(er.ToString());
                return operationResult;
            }
        }