internal class EmailReaderWriter : IEmailReaderWriter
{
public ConcurrentBag<string> ReadEmails { get; private set; }
public ConcurrentBag<string> WrittenEmails { get; private set; }
public string FolderPath { get; }
private delegate void EmailReaderWriterHandler(string message);
private event EmailReaderWriterHandler SuccessNotification, ErrorNotification;
private FileOptions customFileOptions;
public EmailReaderWriter(string folderpath)
{
FolderPath = folderpath;
ReadEmails = new ConcurrentBag<string>();
WrittenEmails = new ConcurrentBag<string>();
SuccessNotification += OperationSuccessNotifier.Success;
ErrorNotification += OperationSuccessNotifier.Error;
customFileOptions = FileOptions.Asynchronous | FileOptions.SequentialScan;
}
public async Task<ConcurrentBag<string>?> ReadAsync(string filepath)
{
if (!File.Exists(filepath))
{
ErrorNotification($"File {filepath} doesn't exist!");
return null;
}
FileStream fstream = new FileStream(filepath, FileMode.Open,
FileAccess.Read, FileShare.None, 0, customFileOptions);
StreamReader reader = new StreamReader(fstream);
var allEmails = new ConcurrentBag<string>(
(
await reader.ReadToEndAsync()).
Split(new string[] { " ", ". ", ", " }, StringSplitOptions.RemoveEmptyEntries).
Where(x => x.Contains("@gmail.com"))
);
if (allEmails.Count() == 0)
{
reader.Close();
fstream.Close();
ErrorNotification($"0 emails were found!");
return null;
}
ConcurrentBag<string> nonReadEmails = new ConcurrentBag<string>();
int readEmailsAddedCounter = 0;
foreach (var email in allEmails)
{
if (ReadEmails.Contains(email))
{
ErrorNotification($"Email {email} is already read!");
continue;
}
else
{
readEmailsAddedCounter++;
nonReadEmails.Add(email);
ReadEmails.Add(email);
SuccessNotification($"Email {email} is read!");
}
}
if (readEmailsAddedCounter > 0)
SuccessNotification($"Such quantity of emails was read: {readEmailsAddedCounter}!");
reader.Close();
fstream.Close();
allEmails.Clear();
return nonReadEmails;
}
public async Task<bool> WriteAsync(string filepath, string email)
{
if (WrittenEmails.Contains(email))
{
ErrorNotification($"Email {email} is already written on file!");
return false;
}
using (FileStream fstream = new FileStream(filepath, FileMode.Append,
FileAccess.Write, FileShare.None, 0, customFileOptions |
FileOptions.WriteThrough))
{
using (StreamWriter writer = new StreamWriter(fstream))
{
await writer.WriteLineAsync(email);
WrittenEmails.Add(email);
}
}
SuccessNotification($"Email {email} is successfully written on file!");
return true;
}
}