using ClosedXML.Excel;
using System;

namespace AsbCloudInfrastructure.Services.ProcessMap;

internal static class XLExtentions
{
    public static IXLCell SetVal(this IXLCell cell, object value)
    {
        switch (value)
        {
            case DateTime dateTime:
                cell.SetVal(dateTime);
                break;
            case IFormattable formattable:
                cell.SetVal(formattable);
                break;
            case string valueString:
                cell.SetVal(valueString);
                break;
            default:
                cell.Value = value;
                break;
        }

        return cell;
    }

    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, IFormattable value, string format = "0.00")
    {
        cell.Value = value;
        cell.DataType = XLDataType.Number;
        cell.Style.NumberFormat.Format = format;
        return cell;
    }
}