ISEbd-21_Sharonov_I_A_Proje.../ProjectAirline/Forms/FormTicket.cs

109 lines
3.0 KiB
C#

using ProjectAirline.Entities.Enums;
using ProjectAirline.Entities;
using ProjectAirline.Repositories;
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;
using Microsoft.VisualBasic.FileIO;
namespace ProjectAirline.Forms;
public partial class FormTicket : Form
{
private readonly ITicketRepository _ticketRepository;
private int? _ticketId;
public int Id
{
set
{
try
{
var ticket = _ticketRepository.ReadTicketById(value);
if (ticket == null)
{
throw new InvalidDataException(nameof(ticket));
}
foreach (TicketStatus elem in Enum.GetValues(typeof(TicketStatus)))
{
if ((elem & ticket.Status) != 0)
{
checkedListBoxStatus.SetItemChecked(checkedListBoxStatus.Items.IndexOf(elem), true);
}
}
_ticketId = value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
public FormTicket(ITicketRepository ticketRepository)
{
InitializeComponent();
_ticketRepository = ticketRepository ?? throw new ArgumentNullException(nameof(ticketRepository));
foreach (var elem in Enum.GetValues(typeof(TicketStatus)))
{
checkedListBoxStatus.Items.Add(elem);
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
var status = GetTicketStatusFromCheckedListBox();
if (status == TicketStatus.None)
{
throw new Exception("Необходимо выбрать хотя бы один статус");
}
if (_ticketId.HasValue)
{
_ticketRepository.UpdateTicket(CreateTicket(_ticketId.Value));
}
else
{
_ticketRepository.CreateTicket(CreateTicket(0));
}
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private Ticket CreateTicket(int id)
{
var status = GetTicketStatusFromCheckedListBox();
return Ticket.CreateTicket(id, status);
}
private TicketStatus GetTicketStatusFromCheckedListBox()
{
TicketStatus status = TicketStatus.None;
foreach (TicketStatus item in checkedListBoxStatus.CheckedItems)
{
status |= item;
}
return status;
}
}