using System.Globalization;
using System.Windows;
using System.Windows.Media;
using AIStudio.Wpf.DiagramDesigner;
using AIStudio.Wpf.DiagramDesigner.Models;
using AIStudio.Wpf.DiagramDesigner.Services;

namespace AIStudio.Wpf.DiagramDesigner.Additionals.Extensions.ViewModels
{
    public class OutLineTextDesignerItemViewModel : TextDesignerItemViewModel
    {
        private IUIVisualizerService visualiserService;
        public OutLineTextDesignerItemViewModel() : this(null)
        {

        }

        public OutLineTextDesignerItemViewModel(IDiagramViewModel root) : base(root)
        {

        }

        public OutLineTextDesignerItemViewModel(IDiagramViewModel root, SelectableItemBase designer) : base(root, designer)
        {

        }

        public OutLineTextDesignerItemViewModel(IDiagramViewModel root, SerializableItem serializableItem, string serializableType) : base(root, serializableItem, serializableType)
        {

        }

        public override SelectableItemBase GetSerializableObject()
        {
            return new TextDesignerItem(this);
        }

        protected override void Init(IDiagramViewModel root, bool initNew)
        {
            base.Init(root, initNew);

            visualiserService = ApplicationServicesProvider.Instance.Provider.VisualizerService;       
        }

        protected override void InitNew()
        {
            base.InitNew();
            FontViewModel.FontFamily = "Arial";
            FontViewModel.FontSize = 36;
        }

        public void AutoSize()
        {
            var size = MeasureString();
            ItemWidth = size.Width;
            ItemHeight = size.Height;
        }

        private Size MeasureString()
        {
            var formattedText = new FormattedText(
                Text,
                CultureInfo.CurrentUICulture,
                FlowDirection.LeftToRight,
                new Typeface(new FontFamily(FontViewModel.FontFamily), FontViewModel.FontStyle, FontViewModel.FontWeight, FontViewModel.FontStretch),
                FontViewModel.FontSize,
                Brushes.Black);

            return new Size(formattedText.Width, formattedText.Height);
        }

        protected override void ExecuteEditCommand(object parameter)
        {
            EditData();
        }

        public override bool Verify()
        {
            if (string.IsNullOrEmpty(Text))
                return EditData();
            return true;
        }

        public override bool EditData()
        {
            if (IsReadOnly == true) return false;

            OutLineTextDesignerItemData data = new OutLineTextDesignerItemData(this);
            if (visualiserService.ShowDialog(data) == true)
            {
                Text = data.Text;
                FontViewModel = CopyHelper.Mapper(data.FontViewModel);
                AutoSize();
                return true;
            }

            return false;
        }
    }
}
