using System.Data;

namespace GBDD
{
    public partial class Form2 : Form
    {
        private Button editViolationButton;

        public Form2()
        {
            InitializeComponent();
            editViolationButton = new Button();
            editViolationButton.Text = "Редактировать";
            editViolationButton.Location = new Point(51, 215);
            editViolationButton.Size = new Size(238, 47);
            tabPage1.Controls.Add(editViolationButton);

            Load += Form2_Load;
            button1.Click += button1_Click;
            button2.Click += button2_Click;
            button3.Click += button3_Click;
            button4.Click += button4_Click;
            editViolationButton.Click += editViolationButton_Click;
        }

        private void Form2_Load(object? sender, EventArgs e)
        {
            LoadTables();
        }

        private void LoadTables()
        {
            dataGridView1.DataSource = Db.Select($"""
                select *
                from violation_view
                where driver_name ilike '%{textBox1.Text}%'
                order by id desc
                """);

            dataGridView2.DataSource = Db.Select("select * from fine_view order by id desc");
        }

        private int SelectedId(DataGridView grid)
        {
            DataRowView row = (DataRowView)grid.CurrentRow.DataBoundItem;
            return Convert.ToInt32(row["id"]);
        }

        private void button1_Click(object? sender, EventArgs e)
        {
            new AddViolation().ShowDialog();
            LoadTables();
        }

        private void button2_Click(object? sender, EventArgs e)
        {
            int id = SelectedId(dataGridView1);
            Db.Execute($"select delete_violation({id})");
            LoadTables();
        }

        private void editViolationButton_Click(object? sender, EventArgs e)
        {
            int id = SelectedId(dataGridView1);
            new AddViolation(id).ShowDialog();
            LoadTables();
        }

        private void button3_Click(object? sender, EventArgs e)
        {
            int id = SelectedId(dataGridView2);
            Db.Execute($"select mark_fine_paid({id})");
            LoadTables();
        }

        private void button4_Click(object? sender, EventArgs e)
        {
            LoadTables();
        }
    }
}
