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

namespace Register_office.View.TypesV
{
	public partial class SyndromeTypeForm : Form
	{
		private TypeViewModel _viewModel;
		private SyndromeType? _selectedType;
		private string _columnIdName = "SyndromeTypeId";
		private SyndromeType _temp;

		public SyndromeTypeForm()
		{
			InitializeComponent();
			TopMost = true;
			Text = "Справочник синдромов";
			_viewModel = new();
			_viewModel.ConfigureSettingsDGV<SyndromeType>(dgv);
			UpdateDgv();
			UpdateElements();
		}

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

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

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