ProjectLib/ProjectLibrary/Forms/FReader.cs

89 lines
2.5 KiB
C#

using System;
using System.Windows.Forms;
using ProjectLibrary.Entities;
using ProjectLibrary.Repositories;
namespace ProjectLibrary.Forms
{
public partial class FReader : Form
{
private readonly IReaderRepository _readerRepository;
private int? _readerId;
public int ID
{
set
{
try
{
var reader = _readerRepository.ReadReaderById(value);
if (reader == null)
{
throw new InvalidOperationException($"Reader with ID {value} not found.");
}
txtName.Text = reader.Name;
txtReaderTicket.Text = reader.ReaderTicket.ToString();
_readerId = value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "[ Error : wrong data ]", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
public FReader(IReaderRepository readerRepository)
{
InitializeComponent();
_readerRepository = readerRepository ?? throw new ArgumentNullException(nameof(readerRepository));
}
private void SaveBtn_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(txtName.Text) || string.IsNullOrWhiteSpace(txtReaderTicket.Text))
{
throw new Exception("[ Error : blank spaces were left, not enough information ]");
}
var reader = CreateReader();
if (_readerId.HasValue)
{
_readerRepository.UpdateReader(reader);
}
else
{
_readerRepository.CreateReader(reader);
}
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "[ Error : while saving ]", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void DiscardBtn_Click(object sender, EventArgs e)
{
Close();
}
private Reader CreateReader()
{
return Reader.CreateEntity(
_readerId ?? 0,
txtName.Text,
int.Parse(txtReaderTicket.Text)
);
}
}
}