using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using AsbCloudApp.Data;
using AsbCloudApp.Requests.ParserOptions;
using AsbCloudApp.Services;
using ClosedXML.Excel;

namespace AsbCloudInfrastructure;

public abstract class ParserServiceBase<TDto, TOptions> : IParserService<TDto, TOptions>
	where TDto : class, IId
	where TOptions : IParserOptionsRequest
{
	protected readonly IServiceProvider serviceProvider;

	protected ParserServiceBase(IServiceProvider serviceProvider)
	{
		this.serviceProvider = serviceProvider;
	}

	public abstract ParserResultDto<TDto> Parse(Stream file, TOptions options);
	public abstract Stream GetTemplateFile();

	protected virtual ParserResultDto<TDto> ParseExcelSheet(IXLWorksheet sheet,
		Func<IXLRow, ValidationResultDto<TDto>> parseRow,
		int columnCount,
		int headerRowsCount = 0)
	{
		if (sheet.RangeUsed().RangeAddress.LastAddress.ColumnNumber < columnCount)
			throw new FileFormatException($"Лист {sheet.Name} содержит меньшее количество столбцов.");

		var count = sheet.RowsUsed().Count() - headerRowsCount;

		if (count > 1024)
			throw new FileFormatException($"Лист {sheet.Name} содержит слишком большое количество строк.");

		if (count <= 0)
			return new ParserResultDto<TDto>();

		var dtos = new List<ValidationResultDto<TDto>>(count);
		var warnings = new List<ValidationResult>();

		for (var i = 0; i < count; i++)
		{
			var row = sheet.Row(1 + i + headerRowsCount);

			try
			{
				var dto = parseRow.Invoke(row);
				dtos.Add(dto);
			}
			catch (FileFormatException ex)
			{
				var warning = new ValidationResult(ex.Message);
				warnings.Add(warning);
			}
		}

		var parserResult = new ParserResultDto<TDto>
		{
			Item = dtos
		};

		if (warnings.Any())
			parserResult.Warnings = warnings;

		return parserResult;
	}
}