#if AVALONIA
using Avalonia.Media;
using AvaloniaEdit.Document;
#else
using System.Windows;
using System.Windows.Media;
using ICSharpCode.AvalonEdit.Document;
#endif
using System;
using System.Collections.Generic;

namespace RoslynPad.Editor
{
    public sealed class TextMarker : TextSegment
    {
        private readonly TextMarkerService _service;

        private Color? _backgroundColor;

        private FontStyle? _fontStyle;

        private FontWeight? _fontWeight;

        private Color? _foregroundColor;

        private Color _markerColor;

        public TextMarker(TextMarkerService service, int startOffset, int length)
        {
            _service = service ?? throw new ArgumentNullException(nameof(service));
            StartOffset = startOffset;
            Length = length;
        }

        public bool IsDeleted => !IsConnectedToCollection;

        public Color? BackgroundColor
        {
            get => _backgroundColor;
            set
            {
                if (!EqualityComparer<Color?>.Default.Equals(_backgroundColor, value))
                {
                    _backgroundColor = value;
                    Redraw();
                }
            }
        }

        public Color? ForegroundColor
        {
            get => _foregroundColor;
            set
            {
                if (!EqualityComparer<Color?>.Default.Equals(_foregroundColor, value))
                {
                    _foregroundColor = value;
                    Redraw();
                }
            }
        }

        public FontWeight? FontWeight
        {
            get => _fontWeight;
            set
            {
                if (_fontWeight != value)
                {
                    _fontWeight = value;
                    Redraw();
                }
            }
        }

        public FontStyle? FontStyle
        {
            get => _fontStyle;
            set
            {
                if (_fontStyle != value)
                {
                    _fontStyle = value;
                    Redraw();
                }
            }
        }

        public object? Tag { get; set; }

        public Color MarkerColor
        {
            get => _markerColor;
            set
            {
                if (!EqualityComparer<Color>.Default.Equals(_markerColor, value))
                {
                    _markerColor = value;
                    Redraw();
                }
            }
        }

        public object? ToolTip { get; set; }

        public event EventHandler? Deleted;

        public void Delete() => _service.Remove(this);

        internal void OnDeleted() => Deleted?.Invoke(this, EventArgs.Empty);

        private void Redraw() => _service.Redraw(this);
    }
}
