using Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
using Register_office.Model;
using Register_office.ViewModel;
using System.Data;
using System.Xml.Linq;

namespace Register_office.View.PatientV
{
	public partial class PatientForm : Form
	{
		private PatientViewModel _viewModel;
		private Patient? _selectedPatient;
		private string _columnIdName = "PatientId";
		private Patient _temp;

		public PatientForm()
		{
			InitializeComponent();
			TopMost = true;
			Text = "Пациенты";
			_viewModel = new();
			_viewModel.ConfigureSettingsDGV<PatientWrapper>(dgv);
			UpdateDgv();
			UpdateElements();
			btnPrescription.Visible = _viewModel.General.DoctorId != 0;
		}

		private void UpdateElements(bool enableButtons = false)
		{
			if (_selectedPatient == null)
				btnPrescription.Enabled = btnHospital.Enabled = false;
			else
			{
				btnHospital.Enabled = _selectedPatient.HospitalAdmissions.Count != 0;
				btnPrescription.Enabled = _selectedPatient.Prescriptions.Count != 0;
			}
			btnUpdate.Enabled = btnDelete.Enabled = enableButtons;
		}

		private void UpdateDgv()
		{
			_viewModel.SetDefaultDataSource(dgv);
		}

		private void dgv_SelectionChanged(object sender, EventArgs e)
		{
			if (dgv.SelectedRows.Count != 0 && !dgv.CurrentRow.IsNewRow)
			{
				DataGridViewRow selectedRow = dgv.SelectedRows[0];
				int id = int.Parse(selectedRow.Cells[_columnIdName].Value.ToString() ?? "");
				_selectedPatient = _viewModel.GetPatient(id).FirstOrDefault();
				if (_selectedPatient != null)
					UpdateElements(true);
			}
		}

		private void btnUpdate_Click(object sender, EventArgs e)
		{
			if (_selectedPatient != null)
			{
				PatientDataForm pf = new(_selectedPatient);
				if (pf.ShowDialog() == DialogResult.OK)
				{
					UpdateElements();
					UpdateDgv();
				}
			}
		}

		private void btnDelete_Click(object sender, EventArgs e)
		{
			if (_selectedPatient != null)
			{
				_viewModel.DeletePatient(_selectedPatient);
				UpdateElements();
				UpdateDgv();
			}
		}

		private void btnPrescription_Click(object sender, EventArgs e)
		{
			PrescriptionForm pf = new(_selectedPatient);
			pf.ShowDialog();
		}

		private void btnHospital_Click(object sender, EventArgs e)
		{
			HospitalForm hf = new(_selectedPatient);
			hf.ShowDialog();
		}
	}
}
