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

namespace Register_office.View.TypesV
{
	public partial class ExaminationTypeForm : Form
	{
		private TypeViewModel _viewModel;
		private ExaminationType? _selectedType;
		private string _columnIdName = "ExaminationTypeId";
		private ExaminationType _temp;

		public ExaminationTypeForm()
		{
			InitializeComponent();
			TopMost = true;
			Text = "Справочник обследований";
			_viewModel = new();
			_viewModel.ConfigureSettingsDGV<ExaminationType>(dgv);
			UpdateDgv();
			UpdateElements();
		}

		private void UpdateElements(string txt1 = "", string txt2 = "", bool enableButtons = false)
		{
			tbName.Text = txt1;
			cbCategory.Text = txt2;
			btnDelete.Enabled = btnUpdate.Enabled = enableButtons;
		}

		private void UpdateDgv()
		{
			_viewModel.SetDefaultDataSource<ExaminationType>(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.ExaminationTypes.Where(x => x.ExaminationTypeId == id).FirstOrDefault();
				if (_selectedType != null)
					UpdateElements(_selectedType.Name, _selectedType.Category, true);
			}
		}

		private void btnUpdate_Click(object sender, EventArgs e)
		{
			if (_selectedType != null)
			{
				_selectedType.Name = tbName.Text;
				_selectedType.Category = cbCategory.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)
		{
			_temp = new()
			{
				Name = tbName.Text,
				Category = cbCategory.Text
			};
			_viewModel.AddType(_temp);
			UpdateElements();
			UpdateDgv();
		}
	}
}
