using AntiAircraftGun.CollectionGenereticObject; using AntiAircraftGun.CollectionGenereticObjects; using AntiAircraftGun.CollectionGenericObjects; using AntiAircraftGun.Drawnings; using AntiAircraftGun.Exceptions; using Microsoft.Extensions.Logging; namespace AntiAircraftGun; /// /// Форма работы с компанией и ее коллекцией /// public partial class FormArmoredCarCollection : Form { /// /// Хранилише коллекций /// private readonly StorageCollection _storageCollection; /// /// Компания /// private AbstractCompany? _company = null; /// /// Логгер /// private readonly ILogger _logger; /// /// Конструктор /// public FormArmoredCarCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); _logger = logger; } /// /// Выбор компании /// /// /// private void comboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) { panelCompanyTools.Enabled = false; } /// /// Добавление машины /// /// /// private void buttonAddArmoredCar_Click(object sender, EventArgs e) { FormCarConfig form = new(); form.Show(); form.AddEvent(SetCar); } /// /// Добавление машины в коллекции /// /// private void SetCar(DrawningArmoredCar? armoredCar) { try { if (_company == null || armoredCar == null) { return; } if (_company + armoredCar != -1) { MessageBox.Show("Объект добавлен"); pictureBox.Image = _company.Show(); } } catch (CollectionOverflowException) { MessageBox.Show("Не удалось добавить объект"); } } /// /// Удаление объекта /// /// /// private void buttonRemoveArmoredCar_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) { return; } if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) { return; } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); try { if (_company - pos != null) { MessageBox.Show("Объект удален"); pictureBox.Image = _company.Show(); } else { MessageBox.Show("Не удалось удалить объект"); } } catch (PositionOutOfCollectionException) { MessageBox.Show("Ошибка при удалении объекта"); } catch (Exception) { MessageBox.Show("Неизвестная ошибка при удалении объекта"); } } /// /// Перерисовка коллекции /// /// /// private void buttonRefresh_Click(object sender, EventArgs e) { if (_company == null) { return; } try { pictureBox.Image = _company.Show(); } catch (PositionOutOfCollectionException) { } catch (Exception) { } } /// /// Передача объекта в другую форму /// /// /// private void buttonGoToChek_Click(object sender, EventArgs e) { if (_company == null) { return; } DrawningArmoredCar? armoredcar = null; int counter = 100; while (armoredcar == null) { armoredcar = _company.GetRandomObject(); counter--; if (counter <= 0) { break; } } if (armoredcar == null) { return; } FormAntiAircraftGun form = new() { SetArmoredCar = armoredcar }; form.ShowDialog(); } /// /// Обновление списка в listBoxCollection /// private void RerfreshListBoxItems() { listBoxCollection.Items.Clear(); for (int i = 0; i < _storageCollection.Keys?.Count; ++i) { string? colName = _storageCollection.Keys?[i]; if (!string.IsNullOrEmpty(colName)) { listBoxCollection.Items.Add(colName); } } } /// /// Добавление коллекции /// /// /// private void buttonCollectionAdd_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } CollectionType collectionType = CollectionType.None; if (radioButtonMassive.Checked) { collectionType = CollectionType.Massive; } else if (radioButtonList.Checked) { collectionType = CollectionType.List; } _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); RerfreshListBoxItems(); } /// /// Удаление коллекции /// /// /// private void buttonCollectionDel_Click(object sender, EventArgs e) { if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); return; } if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; } _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); RerfreshListBoxItems(); } /// /// Создание комании /// /// /// private void buttonCreateCompany_Click(object sender, EventArgs e) { if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); return; } ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); return; } try { switch (comboBoxSelectorCompany.Text) { case "База": _company = new CarBase(pictureBox.Width, pictureBox.Height, collection); break; } } catch (ObjectNotFoundException) { } panelCompanyTools.Enabled = true; RerfreshListBoxItems(); } /// /// Обработка нажатия "Сохранение" /// /// /// private void SaveToolStripMenuItem_Click(object sender, EventArgs e) { if (saveFileDialog.ShowDialog() == DialogResult.OK) { try { _storageCollection.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName); } catch (Exception ex) { MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError("Ошибка: {Message}", ex.Message); } } } /// /// Обработка нажатия "Загрузка" /// /// /// private void LoadToolStripMenuItem_Click(object sender, EventArgs e) { if (openFileDialog.ShowDialog() == DialogResult.OK) { try { _storageCollection.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); foreach (var collection in _storageCollection.Keys) { listBoxCollection.Items.Add(collection); } RerfreshListBoxItems(); } catch (Exception ex) { MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }