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;
using Электронная_Фармация.Classes;
using System.Data.SQLite;

namespace Электронная_Фармация.Forms
{
    public partial class FConsignees : Form
    {
        public FConsignees()
        {
            InitializeComponent();
        }

        private void FConsignees_Load(object sender, EventArgs e)
        {
            UiThemeHelper.ApplyToControlTree(this);
            showMeContentFromConsigneesTable();
        }

        void showMeContentFromConsigneesTable()
        {
            using (SQLiteConnection conConsignees = new SQLiteConnection(AppConfig.SqliteConnectionString))
            {
                string selectFromConsignees = $@"
select [codeConsignees] as [Код грузополучателя],
[ConsigneesName] as [Наименование],
[ConsigneesAddress] as [Адрес],
[ConsigneesUseAsDefault] as [По умолчанию?]
from [Consignees]
order by [ConsigneesUseAsDefault] desc";
                try
                {
                    conConsignees.Open();
                    SQLiteCommand cmdShowConsigneesList = new SQLiteCommand(selectFromConsignees, conConsignees);
                    DataTable tableConsignees = new DataTable();
                    SQLiteDataAdapter daConsigneeList = new SQLiteDataAdapter(cmdShowConsigneesList);
                    daConsigneeList.Fill(tableConsignees);
                    dgvConsignees.DataSource = tableConsignees;
                    dgvConsignees.Columns[3].ValueType = typeof(float);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Возникла ошибка при заполнении данных о грузополучателях.\nТекст ошибки:\n{ex}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    conConsignees.Close();
                }
            }
        }

        private void txtInteractiveShowMeConsignees_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                if (dgvConsignees.Rows.Count > 0)
                {
                    (dgvConsignees.DataSource as DataTable).DefaultView.RowFilter = string.Format($"[Наименование] like '%{txtInteractiveShowMeConsignees.Text}%'");
                    if (dgvConsignees.Rows.Count == 0)
                    {
                        showMeContentFromConsigneesTable();
                    }
                }
                else
                {
                    showMeContentFromConsigneesTable();
                }
                txtInteractiveShowMeConsignees.Text = string.Empty;
            }
        }

    }
}
