using LDBproject.Entities.Enums;
using LDBproject.Entities;
using LDBproject.Repositories;

namespace LDBproject.AdditionalForms;

public partial class BookF : Form
{
    private readonly IBookRep _bookRepository;
    private int? _bookID;

    public BookF(IBookRep bookR)
    {
        InitializeComponent();
        _bookRepository = bookR ?? throw new ArgumentNullException(nameof(bookR));

        StatusCbox.DataSource = Enum.GetValues(typeof(BookStat));

        // Populate the checkbox list with enum values as before
        foreach (var elem in Enum.GetValues(typeof(Genres)))
        {
            GenresChBoxList.Items.Add(elem);
        }
    }

    public int ID
    {
        set
        {
            try
            {
                var book = _bookRepository.GetBookByID(value);

                if (book == null)
                {
                    throw new InvalidDataException(nameof(book));
                }

                // Clear all checkboxes
                for (int i = 0; i < GenresChBoxList.Items.Count; i++)
                {
                    GenresChBoxList.SetItemChecked(i, false);
                }

                // Check the checkboxes based on the book's GenreIDs
                foreach (Genres genre in Enum.GetValues(typeof(Genres)))
                {
                    if ((genre & book.GenreMask) != 0)
                    {
                        int index = GenresChBoxList.Items.IndexOf(genre);
                        if (index != -1)
                        {
                            GenresChBoxList.SetItemChecked(index, true);
                        }
                    }
                }

                TitleTb.Text = book.Title;
                AuthorTb.Text = book.Author;
                YearNud.Value = book.PublishYear;
                StatusCbox.SelectedItem = book.Status;

                _bookID = value;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "BookF [ Error : wrong data ]", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }
    }

    private void SaveBtn_Click(object sender, EventArgs e)
    {
        try
        {
            if (string.IsNullOrWhiteSpace(TitleTb.Text)
                || GenresChBoxList.CheckedItems.Count == 0
                || StatusCbox.SelectedIndex < 1)
            {
                throw new Exception("BookF [ Blank spaces were left, not enough information ]");
            }

            if (_bookID.HasValue)
            {
                _bookRepository.UpdateBook(CreateBook(_bookID.Value));
            }
            else
            {
                _bookRepository.AddBook(CreateBook(0));
            }

            Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "BookF [ Error : while saving ]",
                MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void DiscardBtn_Click(object sender, EventArgs e) => Close();

    private Book CreateBook(int id)
    {
        Genres selectedGenres = Genres.None;
        foreach (var item in GenresChBoxList.CheckedItems)
        {
            if (item is Genres genre)
                selectedGenres |= genre;
        }

        return Book.AddBook(id, TitleTb.Text, AuthorTb.Text,
            (int)YearNud.Value, selectedGenres, (BookStat)StatusCbox.SelectedItem!);
    }
}