// POST: api/MonitorFaxes
 public IHttpActionResult Post(int id,[FromBody]string value)
 {
     FaxRepository faxData = new FaxRepository();
     bool returnValue = faxData.RemoveFromMonitoringFaxList(id.ToString());
     if (returnValue)
     {
         return Ok();
     }
     else{
         return BadRequest();
     }
 }
 // POST: api/SendToUser
 public IHttpActionResult Post([FromBody]FaxFolders sendTo)
 {
     try
     {
         FaxRepository faxData = new FaxRepository();
         faxData.SendFileToAnotherUser(sendTo);
         return Ok();
     }
     catch
     {
         return BadRequest();
     }
 }
        // GET: api/HoldFolders/5
        public IEnumerable<InboundFaxDocument> Get(string id)
        {
            if (id == "S" | id == "I" | id == "P" )
            {
                FaxRepository FaxData = new FaxRepository();
                return FaxData.GetHoldFolders(id);
            }
            else
            {

                FaxRepository faxData = new FaxRepository();
                return faxData.GetFilesInFolder(id);
            }
        }
        // GET: api/FolderList/5
        public IEnumerable<KendoTreeViewViewModel> Get(string id)
        {
            FaxRepository faxData = new FaxRepository();

            string path = string.Empty;

            if (id.Substring(1, 1) == ":")
            {
                path = id;
            }
            else
            {
                path = ConfigurationValues.DefaultFolderFaxes;
            }

            var directories = Directory.GetDirectories(path).Select(dir =>
                new KendoTreeViewViewModel
                {
                    Id = dir,
                    HasChildren = true,
                    Name = Path.GetFileName(dir)
                });


            var result = directories.ToList();

            for (int i = 0; i < result.Count; i++)
            {
                string newName = faxData.GetPostOfficeFaxFolderTranslation(result[i].Name);
                if (newName != "None")
                {
                    result[i].Name = newName;
                }
            }

            //result.AddRange(directories);
            result = result.OrderBy(x => x.HasChildren).ToList();

            FolderRepository folderData = new FolderRepository();

            for (int i = 0; i < result.Count; i++)
            {
                result[i] = folderData.GetCheckedFolders(result[i]);
            }
            return result;
        }
        // GET: api/ViewSplitDocument
        public SplitDocument Get(string id)
        {
            DocumentRepository documentData = new DocumentRepository();
            FaxRepository faxData = new FaxRepository();
            string fullPath = faxData.GetFullPathInboundFax(id);

            //CurrentDocuments currentPDFDocument = documentData.GetCurrentDocumentPathPDF(Utility.GetUserName());
            SplitDocument splitDocument = new SplitDocument();
            string[] path = fullPath.Split('\\');

            splitDocument.Path = ConfigurationValues.PdfFolder + path[path.Length - 1];
            File.Copy(fullPath,
                ConfigurationValues.WhereToCopyPDfTo + path[path.Length - 1], true );

            splitDocument.PageCount = Utility.GetPDFPageCount(ConfigurationValues.WhereToCopyPDfTo + path[path.Length - 1]);

            return splitDocument;
        }
        // GET: api/SendFaxAgain
        public string Get()
        {

            var queryString = this.Request.GetQueryNameValuePairs().ToList();

            string sendID = queryString[0].Value;
            string faxNumber = queryString[1].Value;


            FaxRepository faxData = new FaxRepository();
            bool returnValue = faxData.SendFaxAgain(faxNumber, sendID);
            if (returnValue)
            {

            }
            else
            {

            }

            return "OK";
        }
 // POST: api/MoveFilesPrint
 public void Post([FromBody]MoveFile moveFile)
 {
     FaxRepository faxData = new FaxRepository();
     faxData.MoveFileToPrintFolder(moveFile);
 }
 // GET: api/MoveFilesPrint/5
 public string Get(string id)
 {
     FaxRepository faxData = new FaxRepository();
     return faxData.MoveResendFileToView(id);
 }
        // GET: api/InboundFax/5
        public HttpResponseMessage Get(string id)
        {

            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);

            try
            {
                Logging.LogErrors(ConfigurationValues.ErrorLogPath, ConfigurationValues.PdfTronLicenseKey);

                PDFNet.Initialize(ConfigurationValues.PdfTronLicenseKey);
                PDFDoc documentToAdd = new PDFDoc();
                string xodFileName = Guid.NewGuid().ToString() + ".xod";
                string pdfFileName = xodFileName.Replace(".xod", ".pdf");

                string filePathXod = ConfigurationValues.PathToXodFile + xodFileName;
                string filePathPdf = ConfigurationValues.PathToXodFile + pdfFileName;
                PDFDoc newDocument = new PDFDoc();

                if (string.IsNullOrEmpty(id))
                {
                    try
                    {
                        File.Delete(filePathXod);
                    }
                    catch { }
                    File.Create(filePathXod).Dispose();
                    result = new HttpResponseMessage(HttpStatusCode.OK);
                    var stream = new FileStream(filePathXod, FileMode.Open);
                    result.Content = new StreamContent(stream);
                    result.Content.Headers.ContentType =
                        new MediaTypeHeaderValue("application/octet-stream");
                    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                    {
                        FileName = ConfigurationValues.XodFileName
                    };
                    return result;
                }
                else
                {
                    string[] documents = id.Split('~');

                    for (int i = 0; i < documents.Length - 1; i++)
                    {
                        FaxRepository faxData = new FaxRepository();
                        //documentToAdd = new PDFDoc(faxData.GetFullPathInboundFax(documents[i]));
                        documentToAdd = new PDFDoc(documents[i]);
                        PageIterator itr = documentToAdd.GetPageIterator();
                        for (; itr.HasNext(); itr.Next())
                        {
                            try
                            {
                                pdftron.PDF.Page page = itr.Current();
                                newDocument.PageInsert(newDocument.GetPageIterator(itr.GetPageNumber()), page);
                            }
                            catch (Exception er)
                            {
                                string s1 = er.ToString();
                            }
                        }
                    }
                    try
                    {
                        File.Delete(filePathXod);
                    }
                    catch { }

                    documentToAdd.Close();
                    documentToAdd.Dispose();
                    DocumentRepository documentData = new DocumentRepository();
                    documentData.AddUpdateCurrentDocument(Utility.GetUserName(), filePathXod, filePathPdf, id, documentData.GetFullPathToDocument(Utility.GetUserName()));
                    File.Create(filePathXod).Dispose();
                    newDocument.Save(filePathPdf, 0);
                    pdftron.Filters.Filter objFilter = pdftron.PDF.Convert.ToXod(newDocument);
                    System.Threading.Thread.Sleep(ConfigurationValues.XodSaveDelay);
                    objFilter.WriteToFile(filePathXod, true);
                    var stream = new FileStream(filePathXod, FileMode.Open);
                    result.Content = new StreamContent(stream);
                    result.Content.Headers.ContentType =
                        new MediaTypeHeaderValue("application/octet-stream");
                    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                    {
                        FileName = ConfigurationValues.XodFileName
                    };
                    newDocument.Close();
                    newDocument.Dispose();
                }
                return result;
            }
            catch (Exception er)
            {
                Logging.LogErrors(ConfigurationValues.ErrorLogPath, er.ToString());
                return result;
            }
        }
 // GET: api/InboundFax
 public IEnumerable<InboundFaxDocument> Get()
 {
     FaxRepository FaxData = new FaxRepository();
     return FaxData.GetInboundFaxList();
 }
        // 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/MonitorFaxes
 public IEnumerable<MonitorFax> Get()
 {
     FaxRepository faxData = new FaxRepository();
     return faxData.FaxHistory(Utility.GetUserName());
 }
 // POST: api/HoldFolders
 public void Post([FromBody]Folder folder)
 {
    FaxRepository FaxData = new FaxRepository();
    OperationResult OperationResult = FaxData.AddFolder(folder);
 }
        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;
            }
        }