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 db_lab
{
    public partial class DepartmentForm : Form
    {
        private DepartmentRepository departmentRepository;
        private int pageSize = 10;
        private int currentPage = 1;

        public DepartmentForm(string connectionString)
        {
            InitializeComponent();
            departmentRepository = new DepartmentRepository(connectionString);
            LoadData();
        }

        private void LoadData()
        {
            DataTable dt = departmentRepository.ReadDepartments(pageSize, currentPage);
            dataGridView1.DataSource = dt;
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            currentPage++;
            LoadData();
        }

        private void btnPrev_Click(object sender, EventArgs e)
        {
            if (currentPage > 1)
            {
                currentPage--;
                LoadData();
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in dataGridView1.SelectedRows)
            {
                int code = Convert.ToInt32(row.Cells["code"].Value);
                departmentRepository.DeleteDepartment(code);
            }
            LoadData();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            EditDepartmentForm editForm = new EditDepartmentForm(departmentRepository);
            editForm.ShowDialog();
            LoadData();
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count == 1)
            {
                int code = Convert.ToInt32(dataGridView1.SelectedRows[0].Cells["code"].Value);
                EditDepartmentForm editForm = new EditDepartmentForm(departmentRepository, code);
                editForm.ShowDialog();
                LoadData();
            }
            else
            {
                MessageBox.Show("Please select a single row to edit.");
            }
        }
    }
}
