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 EditDepartmentForm : Form
    {
        private DepartmentRepository departmentRepository;
        private int? departmentCode;

        public EditDepartmentForm(DepartmentRepository departmentRepository, int? departmentCode = null)
        {
            InitializeComponent();
            this.departmentRepository = departmentRepository;
            this.departmentCode = departmentCode;
            if (departmentCode.HasValue)
            {
                LoadRecordData(departmentCode.Value);
            }
        }

        private void LoadRecordData(int code)
        {
            DataRow row = departmentRepository.GetDepartmentByCode(code);
            if (row != null)
            {
                textBoxCode.Text = row["code"].ToString();
                textBoxName.Text = row["name"].ToString();
                textBoxFloor.Text = row["floor"].ToString();
                textBoxCreatingUserId.Text = row["creating_user_id"].ToString();
                textBoxBuildingId.Text = row["building_id"].ToString();
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            int code = int.Parse(textBoxCode.Text);
            string name = textBoxName.Text;
            int floor = int.Parse(textBoxFloor.Text);
            int creatingUserId = int.Parse(textBoxCreatingUserId.Text);
            int buildingId = int.Parse(textBoxBuildingId.Text);

            if (departmentCode.HasValue)
            {
                departmentRepository.UpdateDepartment(code, name, floor, creatingUserId, buildingId);
            }
            else
            {
                departmentRepository.AddDepartment(code, name, floor, creatingUserId, buildingId);
            }
            this.Close();
        }
    }
}
