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

namespace Register_office.View.TypesV
{
	public partial class DiseaseForm : Form
	{
		private TypeViewModel _viewModel;
		private Disease? _selectedType;
		private string _columnIdName = "DiseaseId";
		
		public DiseaseForm()
		{
			InitializeComponent();
			Text = "Справочник заболеваний";
			TopMost = true;
			_viewModel = new();
			_viewModel.ConfigureSettingsDGV<Disease>(dgv);
			UpdateDgv();
			UpdateElements();
		}

		private void UpdateElements(string name = "", string codeIcb = "", bool enableButtons = false)
		{
			tbName.Text = name;
			tbCodeICB.Text = codeIcb;
			btnDelete.Enabled = btnUpdate.Enabled = enableButtons;
		}

		private void UpdateDgv()
		{
			_viewModel.SetDefaultDataSource<Disease>(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() ?? "");
				_selectedType = _viewModel.General.Context.Diseases.Where(x => x.DiseaseId == id).FirstOrDefault();
				if (_selectedType != null)
					UpdateElements(_selectedType.Name, _selectedType.IcdCode, true);
			}
		}

		private void btnUpdate_Click(object sender, EventArgs e)
		{
			if (_selectedType != null)
			{
				_selectedType.Name = tbName.Text;
				_selectedType.IcdCode = tbCodeICB.Text;
				_viewModel.General.Context.SaveChanges();
				UpdateElements();
				UpdateDgv();
			}
		}

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

		private void btnAdd_Click(object sender, EventArgs e)
		{
			Disease d = new()
			{
				Name = tbName.Text,
				IcdCode = tbCodeICB.Text
			};
			_viewModel.AddType(d);
			UpdateElements();
			UpdateDgv();
		}
	}
}
