using BusinessLogic;
using ComponentsLibraryNet60.DocumentWithChart;
using ComponentsLibraryNet60.DocumentWithTable;
using ComponentsLibraryNet60.Models;
using Contracts.BindingModels;
using Contracts.BusinessLogicContracts;
using Contracts.SearchModels;
using Contracts.ViewModels;
using CustomComponents;
using DatabaseImplement.Implements;
using KOP_Labs;
using KOP_Labs.Classes;
using KOP_Labs.NonVisualComponents;
using PluginsConventionLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ViewComponents.NotVisualComponents;

namespace Library
{
	public class PluginsConvention : IPluginsConvention
	{
		private readonly IBookLogic _bookLogic;
		private readonly IAuthorLogic _authorLogic;
		private readonly KOP_Labs.TableComponent _controlDataTable;
		private readonly PdfImages _pdfImagesComponent;
		private readonly ComponentDocumentWithTableHeaderRowExcel _excelTableComponent;
		private readonly WordHistogramm _chartBar;
		public string PluginName { get; set; } = "LabWork_03_plugin";

		public UserControl GetControl
		{
			get { return _controlDataTable; }
		}

		public PluginsConvention()
		{
			_bookLogic = new BookLogic(new BookStorage());
			_authorLogic = new AuthorLogic(new AuthorStorage());
			_pdfImagesComponent = new();
			_excelTableComponent = new();
			_chartBar = new();
			_controlDataTable = new();
		}

		public PluginsConventionElement GetElement
		{
			get
			{
				int Id = _controlDataTable.GetSelectedObject<BookSearchModel>()!.Id;
				byte[] bytes = new byte[16];
				BitConverter.GetBytes(Id).CopyTo(bytes, 0);
				Guid guid = new Guid(bytes);
				return new PluginsConventionElement() { Id = guid };
			}
		}

		public Form GetForm(PluginsConventionElement element)
		{
			if (element == null)
			{
				return new FormBook(_bookLogic, _authorLogic);
			}
			else
			{
				FormBook form = new FormBook(_bookLogic, _authorLogic);
				form.Id = element.Id.GetHashCode();
				return form;
			}
		}

		public Form GetThesaurus()
		{
			return new FormAuthor(_authorLogic);
		}

		public bool DeleteElement(PluginsConventionElement element)
		{
			_bookLogic.Delete(
				new BookBindingModel { Id = element.Id.GetHashCode() }
			);
			return true;
		}

		public void ReloadData()
		{
			try
			{
				var list = _bookLogic.Read(null);
				if (list != null)
				{
					_controlDataTable.ClearRows();

					_controlDataTable.TableConfiguration(5, new List<TableParameters>
					{
						new TableParameters("Id", 80, false, "Id"),
						new TableParameters("Название", 100, true, "Name"),
						new TableParameters("Автор", 180, true, "Author"),
						new TableParameters("Обложка", 80, false, "PicturePath"),
						new TableParameters("Дата издания", 150, true, "PublicationDate")
					});

					foreach (var row in list)
					{
						_controlDataTable.AddRow(row);
					}
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(
					ex.Message,
					"Ошибка",
					MessageBoxButtons.OK,
					MessageBoxIcon.Error
				);
			}
		}

		public bool CreateSimpleDocument(PluginsConventionSaveDocument saveDocument)
		{
			List<string> images = new List<string>();
			var list = _bookLogic.Read(null);

			try
			{
				if (list != null)
				{
					foreach (var item in list)
					{
						images.Add(item.PicturePath);
					}
					string[] imagesArray = images.ToArray();

					_pdfImagesComponent.CreatePdfDoc(new ImagesForPDF(saveDocument.FileName, "Иллюстрации книг", imagesArray));
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "Ошибка");
			}
			MessageBox.Show("Документ создан");
			return true;
		}

		public bool CreateTableDocument(PluginsConventionSaveDocument saveDocument)
		{
			List<(int Column, int Row)> width = new List<(int, int)>() { (30, 0), (30, 0), (30, 0), (30, 0) };
			List<(int StartIndex, int Count)> column_union = new List<(int, int)>() { (1, 2) };
			List<(int ColumnIndex, int RowIndex, string Header, string PropertyName)> headers =
				new List<(int ColumnIndex, int RowIndex, string Header, string PropertyName)> {
					(0,0, "Идентификатор", "Id"),
					(1,0,"Книга", ""),
					(1,1,"Название", "Name"),
					(2,1,"Автор","Author"),
					(3,0,"Дата публикации", "PublicationDate")
				};

			var list = _bookLogic.Read(null);

			try
			{
				_excelTableComponent.CreateDoc(new ComponentDocumentWithTableHeaderDataConfig<BookViewModel>()
				{
					Data = list,
					UseUnion = true,
					ColumnsRowsWidth = width,
					ColumnUnion = column_union,
					Headers = headers,
					FilePath = saveDocument.FileName,
					Header = "Отчёт по книгам"
				});
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "Ошибка");
			}
			MessageBox.Show("Документ создан");
			return true;
		}

		public bool CreateChartDocument(PluginsConventionSaveDocument saveDocument)
		{
			System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

			List<DataHistogramm> dataHistogramms = new List<DataHistogramm>();

			var list_author = _authorLogic.Read(null);
			var list_book = _bookLogic.Read(null);
			foreach (var nm in list_author)
			{
				int bk_count = 0;
				foreach (var bk in list_book)
					if (bk.Author.Contains(nm.FIO)) bk_count++;
				dataHistogramms.Add(new DataHistogramm(nm.FIO, bk_count));
			}
			try
			{
				_chartBar.CreateHistogramm(new MyHistogramm(saveDocument.FileName, "Гистограмма", "Авторы и их книги", EnumLegends.Top, dataHistogramms));
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "Ошибка");
			}

			MessageBox.Show("Документ создан");
			return true;
		}
	}
}