using BlogContracts.BindingModels;
using BlogContracts.BusinessLogicContracts;
using BlogContracts.SearchModels;
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 Blog
{
    public partial class FormCategory : Form
    {
        private readonly ICategoryLogic _categoryLogic;

        private int? _id;
        public int Id { set { _id = value; } }
        public FormCategory(ICategoryLogic categoryLogic)
        {
            InitializeComponent();
            _categoryLogic = categoryLogic;

        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBoxCategory.Text))
            {
                MessageBox.Show("Введите название роли", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            try
            {
                var model = new CategoryBindingModel
                {
                    Id = _id ?? 0,
                    Name = textBoxCategory.Text
                };

                var operationResult = _id.HasValue ? _categoryLogic.Update(model) : _categoryLogic.Create(model);

                if (!operationResult)
                {
                    throw new Exception("Ошибка при сохранеии.");
                }

                MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
                DialogResult = DialogResult.OK;

                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }

        private void FormCategory_Load(object sender, EventArgs e)
        {
            if (_id.HasValue)
            {
                try
                {
                    var view = _categoryLogic.ReadElement(new CategorySearchModel { Id = _id.Value });

                    if (view != null)
                    {
                        textBoxCategory.Text = view.Name;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
    }
}