using Microsoft.EntityFrameworkCore;
using Register_office.Model;
using Register_office.ViewModel;

namespace Register_office.View.PatientV
{
	public partial class ProcedureDataForm : Form
	{
		private PrescriptionViewModel _viewModel;
		private Prescription? _prescription;

		public ProcedureDataForm()
		{
			Init();
		}

		public ProcedureDataForm(Prescription p)
		{
			Init();
			SetData(p);
		}

		private void Init()
		{
			InitializeComponent();
			TopMost = true;
			_viewModel = new();
			SetDataSourceToComboBoxes();
			dtpSchedule.Value =
				dtpSchedule.MinDate = DateTime.Now;
			dtpSchedule.MaxDate = DateTime.Now.AddDays(180);
		}

		private void SetData(Prescription prescription)
		{
			_prescription = prescription;
			cbPatient.SelectedValue = prescription.PatientId;
			dtpSchedule.Value =
				dtpSchedule.MinDate = prescription.ProcedureTypePrescription.ScheduledDatetime;
			cbProcedure.SelectedValue = prescription.ProcedureTypePrescription.ProcedureTypeId;

			Text = "Просмотр процедуры";
			btnOK.Visible = cbPatient.Enabled = 
				dtpSchedule.Enabled	= cbProcedure.Enabled= false;
		}

		private void SetDataSourceToComboBoxes()
		{
			cbProcedure.DataSource = _viewModel.General.Context.ProcedureTypes
				.Select(x => new ComboBoxItem { Name = x.Name, Id = x.ProcedureTypeId })
				.OrderBy(cbi => cbi.Name).ToList();
			cbProcedure.DisplayMember = "Name";
			cbProcedure.ValueMember = "Id";

			cbPatient.DataSource = _viewModel.General.Context.Patients
				.Include(x => x.PatientNavigation)
				.Select(x => new ComboBoxItem
				{
					Name = x.PatientNavigation.FirstName + " " +
							x.PatientNavigation.FirstName + " " +
							x.PatientNavigation.LastName,
					Id = x.PatientId
				})
				.OrderBy(cbi => cbi.Name).ToList();
			cbPatient.DisplayMember = "Name";
			cbPatient.ValueMember = "Id";
		}

		private void btnOK_Click(object sender, EventArgs e)
		{
			Prescription p = new()
			{
				DoctorId = _viewModel.General.DoctorId,
				PatientId = int.Parse(cbPatient.SelectedValue?.ToString() ?? "-1")
			};

			Prescription? prInDb = _viewModel.General.Context.Prescriptions
				.FirstOrDefault(x => x.PatientId == p.PatientId && x.DoctorId == p.DoctorId);
			int id = prInDb?.PrescriptionId ?? 0;
			if (prInDb == null)
			{
				id = _viewModel.AddPrescription(p);
				if (id == -1)
				{
					DialogResult = DialogResult.None;
					return;
				}
			}

			ProcedureTypePrescription pr = new()
			{
				PrescriptionId = id,
				ProcedureTypeId = int.Parse(cbProcedure.SelectedValue?.ToString() ?? "0"),
				ScheduledDatetime = dtpSchedule.Value
			};
			if (_viewModel.AddPrescription(pr) == -1)
			{
				DialogResult = DialogResult.None;
				return;
			}

			MessageBox.Show("Процедура успешно назначена", "Назначение пользователю",
								MessageBoxButtons.OK, MessageBoxIcon.Information);
			Close();

		}
	}
}
