using System; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using InABox.Clients; using InABox.Core; namespace PRS.Mobile { public interface IDigitalFormDocumentHandler { void LoadDocument(Guid id, Action callback); Guid SaveDocument(byte[] data); void Run(Action status); void Stop(); } public abstract class DigitalFormDocumentHandler : IDigitalFormDocumentHandler { private static String FileName(Guid id) => $"{id}.formdocument"; protected abstract String CachePath { get; } protected abstract bool IsConnected { get; } public void LoadDocument(Guid id, Action callback) { var fullpath = Path.Combine(CachePath, FileName(id)); if (File.Exists(fullpath)) callback(File.ReadAllBytes(fullpath)); else { new Client().Query( new Filter(x => x.FileName).IsEqualTo(FileName(id)), null, null, (o, e) => { var row = o?.Rows.FirstOrDefault(); if (row != null) callback(row.Get(c => c.Data)); } ); } } public Guid SaveDocument(byte[] data) { Guid result = Guid.NewGuid(); var filename = Path.Combine(CachePath, FileName(result)); File.WriteAllBytes(filename,data); return result; } private CancellationTokenSource? _cancel; public void Stop() { if (_cancel != null) { _cancel.Cancel(); _cancel = null; } } public void Run(Action status) { Stop(); _cancel = new CancellationTokenSource(); Task.Run( () => { bool? previouslyActive = null; while (true && !_cancel.IsCancellationRequested) { var file = Directory.EnumerateFiles(CachePath, "*.formdocument") .FirstOrDefault(); var isActive = !String.IsNullOrWhiteSpace(file); if (isActive != previouslyActive) { previouslyActive = isActive; status(isActive); } if (!String.IsNullOrWhiteSpace(file) && File.Exists(file) && IsConnected) { var data = File.ReadAllBytes(file); var document = new Document() { FileName = Path.GetFileName(file), Data = data, CRC = CoreUtils.CalculateCRC(data), TimeStamp = DateTime.Now, Created = DateTime.Now, CreatedBy = ClientFactory.UserID }; new Client().Save(document, "Uploaded from Mobile Device"); File.Delete(file); } Thread.Sleep(1000); } }, _cancel.Token ); } } public static class DigitalFormDocumentFactory { private static IDigitalFormDocumentHandler? _handler; public static void Run(THandler handler, Action status) where THandler : IDigitalFormDocumentHandler { _handler = handler; _handler.Run(status); } public static void LoadDocument(Guid id, Action callback) => _handler?.LoadDocument(id, callback); public static Guid SaveDocument(byte[] data) => _handler?.SaveDocument(data) ?? Guid.Empty; } }