// Copyright © Selmo Technology GmbH. All Rights Reserved

using Microsoft.AspNetCore.Components;
using SelmoStudio.Hmi.Server.SelmoHmi.Sequence.Model.Dto;
using SelmoStudio.Hmi.Server.Shared.Model.Diagram;
using System.Globalization;

namespace SelmoStudio.Hmi.Server.Shared.Components.BaseComponents
{
    public partial class LogicLayerDiagramComponent : ComponentBase
    {
        private const int MinZoomValue = 1;
        private const int MaxZoomValue = 2;
        private const double ZoomStep = 0.5;
        private const int ScrollContainerTopOffset = 25;

        private double _zoom = 1;
        private string _zoomDisplayValue => _zoom.ToString(CultureInfo.InvariantCulture);

        private string _contentStyle => $"transform: scale({_zoomDisplayValue}); transform-origin: 0 0; position: relative;";

        private string _scrollContainerStyle => $"flex-grow: 1; overflow: auto; margin-top: {ScrollContainerTopOffset}px; height: 0;";

        private LogicDiagram _diagram;

        private LogicDiagramStep _activeStep;

        private RenderFragment _diagramContent;

        [Parameter]
        public LogicDiagramStep ActiveStep
        {
            get => _activeStep;
            set
            {
                _activeStep = value;
                DrawDiagram();
            }
        }

        [Parameter]
        public LogicDiagram Diagram
        {
            get => _diagram;
            set
            {
                _diagram = value;
                DrawDiagram();
            }
        }

        private void DrawDiagram()
        {
            _diagramContent = (builder) =>
            {
                builder.AddMarkupContent(0, DiagramSvgMapper.ToHtml(Diagram, ActiveStep));
            };
        }

        protected override Task OnParametersSetAsync()
        {
            if (Width == 0)
            {
                Width = 100;
                WidthUnit = SelmoHmi.Shared.WellKnownTypes.WellKnownLengthUnits.Percentage;
            }

            if (Height == 0)
            {
                Height = 100;
                HeightUnit = SelmoHmi.Shared.WellKnownTypes.WellKnownLengthUnits.Percentage;
            }

            return base.OnParametersSetAsync();
        }

        private async Task ZoomIn()
        {
            if (_zoom < MaxZoomValue)
            {
                _zoom += ZoomStep;
            }
        }

        private async Task ZoomOut()
        {
            if (_zoom > MinZoomValue)
            {
                _zoom -= ZoomStep;
            }
        }
    }
}