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

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

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

		private void UpdateDgv()
		{
			_viewModel.SetDefaultDataSource<DrugIntakeMethod>(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.DrugIntakeMethods.Where(x => x.DrugIntakeMethodId == 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)
		{
			DrugIntakeMethod t = new()
			{
				Name = tbName.Text
			};
			_viewModel.AddType(t);
			UpdateElements();
			UpdateDgv();
		}
	}
}
