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

namespace Register_office.View.TypesV
{
	public partial class DrugTypeForm : Form
	{
		private TypeViewModel _viewModel;
		private DrugType? _selectedType;
		private string _columnIdName = "DrugTypeId";
		private DrugType _temp;

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

		private void UpdateElements(string nameRu = "", string? nameEn = "", 
			string? nameLa = "", string? brand = "", bool enableButtons = false)
		{
			tbNameRu.Text = nameRu;
			tbNameEn.Text = nameEn;
			tbNameLa.Text = nameLa;
			tbBrand.Text = brand;
			btnDelete.Enabled = btnUpdate.Enabled = enableButtons;
		}

		private void UpdateDgv()
		{
			_viewModel.SetDefaultDataSource<DrugType>(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.DrugTypes.Where(x => x.DrugTypeId == id).FirstOrDefault();
				if (_selectedType != null)
					UpdateElements(_selectedType.InternationalNameRu, 
						_selectedType.InternationalNameEn, _selectedType.InternationalNameLa,
						_selectedType.BrandNameRu, true);
			}
		}

		private void btnUpdate_Click(object sender, EventArgs e)
		{
			if (_selectedType != null)
			{
				_selectedType.InternationalNameRu = tbNameRu.Text;
				_selectedType.InternationalNameEn = tbNameEn.Text.Trim() == "" ? null : tbNameEn.Text;
				_selectedType.InternationalNameLa = tbNameLa.Text.Trim() == "" ? null : tbNameLa.Text;
				_selectedType.BrandNameRu = tbBrand.Text.Trim() == "" ? null : tbBrand.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()
			{
				InternationalNameRu = tbNameRu.Text,
				InternationalNameEn = tbNameEn.Text.Trim() == "" ? null : tbNameEn.Text,
				InternationalNameLa = tbNameLa.Text.Trim() == "" ? null : tbNameLa.Text,
				BrandNameRu = tbBrand.Text.Trim() == "" ? null : tbBrand.Text
			};
			_viewModel.AddType(_temp);
			UpdateElements();
			UpdateDgv();
		}
	}
}
