using FastReport.SVG;
using FastReport.Utils;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Text;
using Microsoft.AspNetCore.Components;

namespace FastReport.Web.Blazor.Export
{

    public partial class BlazorExport
    {

        /// <inheritdoc/>
        protected override void ExportBand(BandBase band)
        {
            ExportBandLayers(band);
        }

        private bool HasExtendedExport(ReportComponentBase obj)
        {
            return obj is SVGObject;
        }

        #region svg

        private string? GetLayerSVG(SVGObject svg, out float Width, out float Height)
        {
            Width = 0;
            Height = 0;

            if (svg != null)
            {
                if (pictures)
                {
                    Width = svg.Width == 0 ? svg.Border.LeftLine.Width : svg.Width;
                    Height = svg.Height == 0 ? svg.Border.TopLine.Width : svg.Height;

                    if (Math.Abs(Width) * Zoom < 1 && Zoom > 0)
                        Width = 1 / Zoom;

                    if (Math.Abs(Height) * Zoom < 1 && Zoom > 0)
                        Height = 1 / Zoom;
                    MemoryStream svgStream = new MemoryStream();
                    if (svg.Grayscale)
                        svg.SVGGrayscale.Write(svgStream);
                    else
                        svg.SvgDocument.Write(svgStream);
                    svgStream.Position = 0;
                    string result = HTMLGetImage(d.CurrentPage, Crypter.ComputeHash(svgStream), svgStream, true);
                    return result;
                }
            }
            return null;
        }

        private void LayerSVG(SVGObject obj)
        {
            if (pictures)
            {
                float Width, Height;
                string? svg = GetLayerSVG(obj, out Width, out Height);

                StringBuilder addstyle = new StringBuilder(64);
                addstyle.Append(defaultStyle);
                addstyle.Append(" background: url('").Append(svg).Append("') center center no-repeat !important;-webkit-print-color-adjust:exact;");
                if (obj.Angle != 0)
                {
                    addstyle.Append($"transform: rotate({obj.Angle}deg);");
                }
                float x = obj.Width > 0 ? obj.AbsLeft : (obj.AbsLeft + obj.Width);
                float y = obj.Height > 0 ? obj.AbsTop : (obj.AbsTop + obj.Height);
                Layer(obj, x, y, obj.Width, obj.Height, null, null, addstyle);

                // cleanup SVG 
                obj.Dispose();
            }
        }

        #endregion
    }
}