using ComputersShopContracts.BindingModels;
using ComputersShopContracts.BusinessLogicContracts;
using Microsoft.Extensions.Logging;
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 ComputersShopView
{
	public partial class FormReportComputerComponents : Form
	{
		private readonly ILogger _logger;
		private readonly IReportLogic _logic;

		public FormReportComputerComponents(ILogger<FormReportComputerComponents> logger, IReportLogic logic)
		{
			InitializeComponent();
			_logger = logger;
			_logic = logic;
		}

		private void FormReportComputerComponents_Load(object sender, EventArgs e)
		{
			try
			{
				var dict = _logic.GetComputerComponents();
				if (dict != null)
				{
					dataGridView.Rows.Clear();
					foreach (var elem in dict)
					{
						dataGridView.Rows.Add(new object[] { elem.ComputerName, "", "" });

						foreach (var listElem in elem.Components)
						{
							dataGridView.Rows.Add(new object[] { "", listElem.Item1, listElem.Item2 });
						}

						dataGridView.Rows.Add(new object[] { "Итого", "", elem.TotalCount });
						dataGridView.Rows.Add(Array.Empty<object>());
					}
				}
				_logger.LogInformation("Loading list of computers by components");
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Error during loading list of computers by components");

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

		private void buttonSaveToExcel_Click(object sender, EventArgs e)
		{
			using var dialog = new SaveFileDialog
			{
				Filter = "xlsx|*.xlsx"
			};

			if (dialog.ShowDialog() == DialogResult.OK)
			{
				try
				{
					_logic.SaveComputerComponentToExcelFile(new ReportBindingModel
					{
						FileName = dialog.FileName
					});

					_logger.LogInformation("Saving list of computers by components");

					MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
				}
				catch (Exception ex)
				{
					_logger.LogError(ex, "Error saving list of computers by components");

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