using Microsoft.VisualBasic.FileIO; using ProjectGarage.Entities; using ProjectGarage.Entities.Enums; using ProjectGarage.Repositories; using ProjectGarage.Repositories.Implementations; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ProjectGarage.Forms { public partial class FormFuel : Form { private readonly IFuelRepository _fuelRepository; private int? _fuelId; public int Id { set { try { var fuel = _fuelRepository.ReadFuelByID(value); if (fuel == null) { throw new InvalidDataException(nameof(fuel)); } foreach (FuelType elem in Enum.GetValues(typeof(FuelType))) { if ((elem & fuel.Type) != 0) { checkedListBoxFuel.SetItemChecked(checkedListBoxFuel.Items.IndexOf(elem), true); } } textBoxFuelName.Text = fuel.Name; _fuelId = value; } catch (Exception ex) { MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } } public FormFuel(IFuelRepository fuelRepository) { InitializeComponent(); _fuelRepository = fuelRepository ?? throw new ArgumentNullException(nameof(fuelRepository)); foreach (var elem in Enum.GetValues(typeof(FuelType))) { checkedListBoxFuel.Items.Add(elem); } } private void ButtonFuelSave_Click(object sender, EventArgs e) { try { if (string.IsNullOrWhiteSpace(textBoxFuelName.Text) || checkedListBoxFuel.CheckedItems.Count == 0) { throw new Exception("Имеются незаполненные поля"); } if (_fuelId.HasValue) { _fuelRepository.UpdateFuel(CreateFuel(_fuelId.Value)); } else { _fuelRepository.CreateFuel(CreateFuel(0)); } Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void ButtonFuelCancel_Click(object sender, EventArgs e) => Close(); private Fuel CreateFuel(int id) { FuelType fuelType = FuelType.None; foreach (var elem in checkedListBoxFuel.CheckedItems) { fuelType |= (FuelType)elem; } return Fuel.CreateFuel(id, textBoxFuelName.Text, fuelType, Convert.ToInt32(numericUpDownFuelPrice.Value)); } } }