using Microsoft.EntityFrameworkCore;
using Register_office.Model;
using Register_office.ViewModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Register_office.View.TypesV
{
	public partial class HospitalDischargeDataForm : Form
	{
		private HospitalViewModel _viewModel;
		private HospitalAdmission _hospitalAdmission;

		public HospitalDischargeDataForm(HospitalAdmission h, bool isForAdd = true)
		{
			Init();
			_hospitalAdmission = h;
			if (!isForAdd) SetData(h);
		}

		private void Init()
		{
			InitializeComponent();
			TopMost = true;
			_viewModel = new();
			SetDataSourceToComboBoxes();
			dtpDischarge.Value = 
				dtpDischarge.MaxDate = DateTime.Now;
		}

		private void SetData(HospitalAdmission ha)
		{
			HospitalDischarge hd = _viewModel.GetHospitalDischarge()
				.First(x => x.HospitalAdmissionId == ha.HospitalAdmissionId);
			cbDisease.SelectedValue = hd.FinalDiseaseId;
			rtbReason.Text = hd.Reason;
			dtpDischarge.Value = hd.DischargeDatetime;

			Text = "Просмотр завершения госпитализации";
			btnOK.Visible = cbDisease.Enabled =
				rtbReason.Enabled = dtpDischarge.Enabled = false;
		}

		private void SetDataSourceToComboBoxes()
		{
			cbDisease.DataSource = _viewModel.General.Context.Diseases
				.Select(x => new ComboBoxItem { Name = x.Name, Id = x.DiseaseId })
				.OrderBy(cbi => cbi.Name).ToList();
			cbDisease.DisplayMember = "Name";
			cbDisease.ValueMember = "Id";
		}

		private void btnOK_Click(object sender, EventArgs e)
		{
			HospitalDischarge hd = new()
			{
				HospitalAdmissionId = _hospitalAdmission.HospitalAdmissionId,
				DischargeDatetime = dtpDischarge.Value,
				FinalDiseaseId = int.Parse(cbDisease.SelectedValue?.ToString() ?? "-1"),
				Reason = rtbReason.Text
			};
			if (_viewModel.AddHospital(hd) == -1)
			{
				DialogResult = DialogResult.None;
				return;
			}

			MessageBox.Show("Госпитализация успешно завершена", "Завершение госпитализации",
								MessageBoxButtons.OK, MessageBoxIcon.Information);
			Close();

		}
	}
}
