using ClosedXML.Excel;
using System;

namespace AsbCloudInfrastructure.Services.ProcessMap;

internal static class XLExtentions
{

    public static IXLCell SetVal(this IXLCell cell, string value, bool adaptRowHeight = false)
    {
        cell.Value = value;
        if (adaptRowHeight)
        {
            var colWidth = cell.WorksheetColumn().Width;
            var maxCharsToWrap = colWidth / (0.1d * cell.Style.Font.FontSize);
            if (value.Length > maxCharsToWrap)
            {
                var row = cell.WorksheetRow();
                var baseHeight = row.Height;
                row.Height = 0.5d * baseHeight * Math.Ceiling(1d + value.Length / maxCharsToWrap);
            }
        }

        return cell;
    }

    public static IXLCell SetVal(this IXLCell cell, DateTime value, string dateFormat = "DD.MM.YYYY HH:MM:SS")
    {
        cell.Value = value;
        cell.DataType = XLDataType.DateTime;
        cell.Style.DateFormat.Format = dateFormat;

        return cell;
    }

    public static IXLCell SetVal(this IXLCell cell, int? value, string format = "0.00")
    {
        cell.Value = value;
        cell.DataType = XLDataType.Number;
        cell.Style.NumberFormat.Format = format;
        return cell;
    }

    public static IXLCell SetVal(this IXLCell cell, double? value, string format = "0.00")
    {
        cell.Value = (value is not null && double.IsFinite(value.Value)) ? value : null;
        cell.DataType = XLDataType.Number;
        cell.Style.NumberFormat.Format = format;
        return cell;
    }

}