namespace GBDD
{
    public partial class AddDriver : Form
    {
        private int driverId = 0;

        public AddDriver()
        {
            InitializeComponent();
            button1.Click += button1_Click;
            button2.Click += button2_Click;
        }

        public AddDriver(int id) : this()
        {
            driverId = id;

            var table = Db.Select($"select * from driver_view where id = {driverId}");
            var row = table.Rows[0];

            textBox1.Text = row["last_name"].ToString();
            textBox4.Text = row["first_name"].ToString();
            textBox3.Text = row["middle_name"].ToString();
            dateTimePicker1.Value = Convert.ToDateTime(row["birth_date"]);
            textBox2.Text = row["city"].ToString();
            textBox5.Text = row["street"].ToString();
            textBox6.Text = row["building"].ToString();
            textBox7.Text = row["apartment"].ToString();
            textBox8.Text = row["postal_code"].ToString();
        }

        private void button1_Click(object? sender, EventArgs e)
        {
            string birthDate = dateTimePicker1.Value.ToString("yyyy-MM-dd");

            if (driverId == 0)
            {
                Db.Execute(SqlQueries.AddDriver(
                    textBox1.Text,
                    textBox4.Text,
                    textBox3.Text,
                    birthDate,
                    textBox2.Text,
                    textBox5.Text,
                    textBox6.Text,
                    textBox7.Text,
                    textBox8.Text));
            }
            else
            {
                Db.Execute($"""
                    select update_driver(
                        {driverId},
                        '{textBox1.Text}',
                        '{textBox4.Text}',
                        '{textBox3.Text}',
                        '{birthDate}',
                        '{textBox2.Text}',
                        '{textBox5.Text}',
                        '{textBox6.Text}',
                        '{textBox7.Text}',
                        '{textBox8.Text}'
                    )
                    """);
            }

            Close();
        }

        private void button2_Click(object? sender, EventArgs e)
        {
            Close();
        }
    }
}
