using System.Data;
using System.Text;

namespace GBDD
{
    public partial class Admin : Form
    {
        private Button editViolationButton;
        private Button editDriverButton;
        private Button exportViolationsButton;

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

            exportViolationsButton = new Button();
            exportViolationsButton.Text = "Экспорт в CSV";
            exportViolationsButton.Location = new Point(50, 372);
            exportViolationsButton.Size = new Size(239, 35);
            tabPage1.Controls.Add(exportViolationsButton);

            editDriverButton = new Button();
            editDriverButton.Text = "Редактировать";
            editDriverButton.Location = new Point(64, 255);
            editDriverButton.Size = new Size(230, 47);
            tabPage3.Controls.Add(editDriverButton);

            Load += Admin_Load;
            button1.Click += button1_Click;
            button2.Click += button2_Click;
            button3.Click += button3_Click;
            button4.Click += button4_Click;
            button5.Click += button5_Click;
            button6.Click += button6_Click;
            editViolationButton.Click += editViolationButton_Click;
            editDriverButton.Click += editDriverButton_Click;
            exportViolationsButton.Click += exportViolationsButton_Click;
        }

        private void Admin_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");

            dataGridView3.DataSource = Db.Select("select * from driver_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();
        }

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

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

        private void editDriverButton_Click(object? sender, EventArgs e)
        {
            int id = SelectedId(dataGridView3);
            new AddDriver(id).ShowDialog();
            LoadTables();
        }

        private void exportViolationsButton_Click(object? sender, EventArgs e)
        {
            using var dialog = new SaveFileDialog();
            dialog.Filter = "CSV файлы (*.csv)|*.csv";
            dialog.FileName = "violations.csv";

            if (dialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            ExportGridToCsv(dataGridView1, dialog.FileName);
            MessageBox.Show("Экспорт нарушений выполнен");
        }

        private static void ExportGridToCsv(DataGridView grid, string fileName)
        {
            using var writer = new StreamWriter(fileName, false, new UTF8Encoding(true));

            var headers = grid.Columns
                .Cast<DataGridViewColumn>()
                .Where(column => column.Visible)
                .Select(column => CsvExporter.EscapeValue(column.HeaderText));

            writer.WriteLine(string.Join(";", headers));

            foreach (DataGridViewRow row in grid.Rows)
            {
                if (row.IsNewRow)
                {
                    continue;
                }

                var values = grid.Columns
                    .Cast<DataGridViewColumn>()
                    .Where(column => column.Visible)
                    .Select(column => CsvExporter.EscapeValue(row.Cells[column.Index].Value?.ToString() ?? string.Empty));

                writer.WriteLine(string.Join(";", values));
            }
        }

    }
}
