using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Rendering;
using FastReport.Web.Blazor.Export;

namespace FastReport.Web.Blazor.Components
{
    public partial class ExportComponent : Microsoft.AspNetCore.Components.ComponentBase
    {

        [Parameter]
        public WebReport WebReport { get; set; }

        /// Main function
        protected override void BuildRenderTree(RenderTreeBuilder builder)
        {
            //Utils.Config.EnableScriptSecurity = false;

            int pageWidth = (int)Math.Ceiling(WebReport.GetReportPageWidthInPixels() * WebReport.Zoom);
            //int pageHeight = (int)Math.Ceiling(WebReport.GetReportPageHeightInPixels() * WebReport.Zoom);
            WebReport.ReportMaxWidth = pageWidth;

            using (BlazorExport blazor = new BlazorExport())
            {
                WebReport.PictureCache.Clear();

                blazor.StylePrefix = $"fr{WebReport.ID}";
                blazor.Pictures = WebReport.Pictures;
                blazor.EmbedPictures = WebReport.EmbedPictures;
                blazor.OnClick += ProcessClick;
                blazor.EnableMargins = WebReport.EnableMargins;
                blazor.Zoom = WebReport.Zoom;

                blazor.PageNumbers = WebReport.SinglePage ? "" : (WebReport.CurrentPageIndex + 1).ToString();

                blazor.WebImagePrefix = WebUtils.ToUrl(FastReportGlobal.FastReportOptions.RoutePathBaseRoot,
                    FastReportGlobal.FastReportOptions.RouteBasePath,
                    $"preview.getPicture?reportId={WebReport.ID}&pictureId=");
                blazor.SinglePage = WebReport.SinglePage;
                blazor.CurPage = WebReport.CurrentPageIndex;

                blazor.Export(WebReport.Report, builder);

                if (!blazor.EmbedPictures)
                    WebReport.CacheHtmlPictures(blazor, blazor.CurPage);

            }
        }


        internal void ProcessClick(object sender, OnClickEventArgs args)
        {
            bool update = WebReport.ProcessClick(sender, args);

            // call Re-render
            if(update)
                WebReport.OnUpdate();                
        }

    }
}
