2023-12-27 20:02:32 +04:00

215 lines
8.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using ElectricLocomotive.DrawningObject;
using ElectricLocomotive.Generics;
using Microsoft.Extensions.Logging;
using ProjectElectricLocomotive;
using ProjectElectricLocomotive.Exceptions;
namespace ElectricLocomotive
{
public partial class FormLocomotiveCollection : Form
{
private readonly LocomotiveGenericStorage _storage;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
public FormLocomotiveCollection(ILogger<FormLocomotiveCollection> logger)
{
InitializeComponent();
_storage = new LocomotiveGenericStorage(CollectionPictureBox.Width, CollectionPictureBox.Height);
_logger = logger;
}
/// <summary>
/// Заполнение listBoxObjects
/// </summary>
private void ReloadObjects()
{
int index = listBoxStorage.SelectedIndex;
listBoxStorage.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxStorage.Items.Add(_storage.Keys[i]);
}
if (listBoxStorage.Items.Count > 0 && (index == -1 || index >= listBoxStorage.Items.Count))
{
listBoxStorage.SelectedIndex = 0;
}
else if (listBoxStorage.Items.Count > 0 && index > -1 && index < listBoxStorage.Items.Count)
{
listBoxStorage.SelectedIndex = index;
}
}
private void ButtonAddObject_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxStorageName.Text))
{
MessageBox.Show("Не всё заполнено", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Неудачная попытка. Коллекция не добавлена, не все данные заполнены");
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
}
private void listBoxStorage_SelectedIndexChanged(object sender, EventArgs e)
{
CollectionPictureBox.Image = _storage[listBoxStorage.SelectedItem?.ToString() ?? string.Empty]?.ShowLocomotives();
}
private void ButtonRemoveObject_Click(object sender, EventArgs e)
{
if (listBoxStorage.SelectedIndex == -1)
{
return;
}
string name = listBoxStorage.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {listBoxStorage.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(name);
ReloadObjects();
_logger.LogInformation($"Набор '{name}' удален");
}
_logger.LogWarning("Отмена удаления набора");
}
private void ButtonAddLocomotive_Click(object sender, EventArgs e)
{
var formLocomotiveConfig = new FormLocomotiveConfig();
formLocomotiveConfig.AddEvent(NAddLocomotive);
formLocomotiveConfig.Show();
}
public void NAddLocomotive(DrawningLocomotive loco)
{
loco._pictureWidth = CollectionPictureBox.Width;
loco._pictureHeight = CollectionPictureBox.Height;
if (listBoxStorage.SelectedIndex == -1) return;
var obj = _storage[listBoxStorage.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
try
{
if (obj + loco > -1)
{
MessageBox.Show("Объект добавлен");
CollectionPictureBox.Image = obj.ShowLocomotives();
_logger.LogInformation($"Добавлен объект {obj}");
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogInformation("Не удалось добавить объект");
}
}
catch (StorageOverflowException ex)
{
MessageBox.Show(ex.Message);
_logger.LogInformation("Не удалось добавить объект");
}
//проверяем, удалось ли нам загрузить объект
}
private void ButtonRemoveLocomotive_Click(object sender, EventArgs e)
{
if (listBoxStorage.SelectedIndex == -1) return;
var obj = _storage[listBoxStorage.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
_logger.LogWarning("Отмена удаления объекта");
return;
}
int pos = Convert.ToInt32(Input.Text);
try
{
if ( obj - pos != null )
{
MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект с позиции{pos}");
CollectionPictureBox.Image = obj.ShowLocomotives();
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Не найден объект по позиции: {pos}");
}
}
catch (LocoNotFoundException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"Не найден объект по позиции: {pos}");
}
}
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
if (listBoxStorage.SelectedIndex == -1) return;
var obj = _storage[listBoxStorage.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
CollectionPictureBox.Image = obj.ShowLocomotives();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.SaveData(saveFileDialog.FileName);
_logger.LogInformation($"Данные загружены в файл {saveFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogWarning($"Не удалось сохранить информацию в файл: {ex.Message}");
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
// TODO продумать логику
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.LoadData(openFileDialog.FileName);
_logger.LogInformation($"Данные загружены из файла {openFileDialog.FileName}");
ReloadObjects();
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogWarning($"Не удалось загрузить информацию из файла: {ex.Message}");
}
}
}
}
}