170 lines
6.9 KiB
C#

using Microsoft.Extensions.Configuration;
using Phares.Shared;
using Serilog;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Text.Json;
using View_by_Distance.Drag_Drop_Explorer.Models;
using View_by_Distance.Shared.Models;
using View_by_Distance.Shared.Models.Stateless.Methods;
namespace View_by_Distance.Drag_Drop_Explorer;
public partial class DragDropExplorer : Form
{
private readonly ILogger _Logger;
private readonly Calendar _Calendar;
private readonly TextBox _PathTextBox;
private readonly TextBox _JsonTextBox;
private readonly TextBox _FirstTextBox;
private readonly AppSettings _AppSettings;
private readonly ProgressBar _ProgressBar;
private readonly string _WorkingDirectory;
private readonly IsEnvironment _IsEnvironment;
public DragDropExplorer()
{
InitializeComponent();
ILogger logger;
AppSettings appSettings;
string workingDirectory;
IsEnvironment isEnvironment;
IConfigurationRoot configurationRoot;
_Calendar = new CultureInfo("en-US").Calendar;
LoggerConfiguration loggerConfiguration = new();
Assembly assembly = Assembly.GetExecutingAssembly();
bool debuggerWasAttachedAtLineZero = Debugger.IsAttached || assembly.Location.Contains(@"\bin\Debug");
isEnvironment = new(processesCount: null, nullASPNetCoreEnvironmentIsDevelopment: debuggerWasAttachedAtLineZero, nullASPNetCoreEnvironmentIsProduction: !debuggerWasAttachedAtLineZero);
IConfigurationBuilder configurationBuilder = new ConfigurationBuilder()
.AddEnvironmentVariables()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile(isEnvironment.AppSettingsFileName, optional: false, reloadOnChange: true)
.AddUserSecrets<Program>();
configurationRoot = configurationBuilder.Build();
appSettings = Models.Binder.AppSettings.Get(configurationRoot);
if (string.IsNullOrEmpty(appSettings.WorkingDirectoryName))
throw new Exception("Working path name must have parentDirectory value!");
workingDirectory = IWorkingDirectory.GetWorkingDirectory(assembly.GetName().Name, appSettings.WorkingDirectoryName);
Environment.SetEnvironmentVariable(nameof(workingDirectory), workingDirectory);
_ = ConfigurationLoggerConfigurationExtensions.Configuration(loggerConfiguration.ReadFrom, configurationRoot);
Log.Logger = loggerConfiguration.CreateLogger();
logger = Log.ForContext<DragDropExplorer>();
logger.Information("Complete");
_Logger = logger;
_AppSettings = appSettings;
_IsEnvironment = isEnvironment;
_WorkingDirectory = workingDirectory;
_ProgressBar = new() { TabIndex = 4, Location = new(5, 5), Dock = DockStyle.Top, Visible = false };
string json = JsonSerializer.Serialize(_AppSettings, new JsonSerializerOptions { WriteIndented = true });
_FirstTextBox = new() { TabIndex = 1, Text = _IsEnvironment.Profile, Location = new(5, 5), Dock = DockStyle.Top };
_PathTextBox = new() { TabIndex = 2, Text = _AppSettings.WorkingDirectoryName, Location = new(5, 5), Dock = DockStyle.Top };
_JsonTextBox = new() { TabIndex = 3, Text = json, Multiline = true, MinimumSize = new(1, 80), Location = new(5, 5), Dock = DockStyle.Top };
Load += new EventHandler(Form1_Load);
Controls.Add(_ProgressBar);
Controls.Add(_JsonTextBox);
Controls.Add(_PathTextBox);
Controls.Add(_FirstTextBox);
}
void Form1_Load(object? sender, EventArgs e)
{
try
{
AllowDrop = true;
DragDrop += new DragEventHandler(Form1_DragDrop);
DragEnter += new DragEventHandler(Form1_DragEnter);
_FirstTextBox.LostFocus += new EventHandler(TextBox_LostFocus);
_PathTextBox.LostFocus += new EventHandler(TextBox_LostFocus);
}
catch (Exception)
{
throw;
}
}
private static string GetConverted(string value)
{
string result = value.Length < 2 || value[1] != ':' ? value : value.Replace("\\\\", "/").Replace('\\', '/');
return result;
}
void TextBox_LostFocus(object? sender, EventArgs e)
{
try
{
if (sender is TextBox textBox)
{
textBox.Text = GetConverted(textBox.Text);
if (textBox.Text == "ps")
throw new NotImplementedException();
}
}
catch (Exception)
{
throw;
}
}
void Form1_DragEnter(object? sender, DragEventArgs e)
{
try
{
if (e.Data is not null && e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
}
catch (Exception)
{
throw;
}
}
void Form1_DragDrop(object? sender, DragEventArgs e)
{
try
{
if (e.Data is null || e.Data.GetData(DataFormats.FileDrop) is not string[] paths || !paths.Any())
{
_FirstTextBox.Text = string.Empty;
_PathTextBox.Text = string.Empty;
_JsonTextBox.Text = string.Empty;
_Logger.Information("No data");
}
else
{
string converted;
FileInfo fileInfo;
List<MatchNginx> files = new();
DateTime dateTime = DateTime.Now;
List<MatchNginx> directories = new();
_FirstTextBox.Text = GetConverted(paths[0]);
string weekOfYear = _Calendar.GetWeekOfYear(dateTime, CalendarWeekRule.FirstDay, DayOfWeek.Sunday).ToString("00");
string directory = Path.Combine(_WorkingDirectory, $"{dateTime.Year}_{weekOfYear}");
if (!Directory.Exists(directory))
_ = Directory.CreateDirectory(directory);
_PathTextBox.Text = GetConverted(Path.Combine(directory, $"{dateTime.Ticks}.json"));
foreach (string path in paths.OrderBy(l => l))
{
fileInfo = new(path);
converted = GetConverted(path);
if (!fileInfo.Exists)
directories.Add(new(fileInfo.Name, "Directory", fileInfo.LastWriteTime, 0, converted));
else
files.Add(new(fileInfo.Name, "File", fileInfo.LastWriteTime, fileInfo.Length, converted));
}
List<MatchNginx> collection = new();
collection.AddRange(directories);
collection.AddRange(files);
_JsonTextBox.Text = JsonSerializer.Serialize(collection, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(_PathTextBox.Text, _JsonTextBox.Text);
}
}
catch (Exception)
{
throw;
}
}
}