using System;
using AIStudio.Wpf.DiagramDesigner;
using AIStudio.Wpf.DiagramDesigner.Models;
using AIStudio.Wpf.DiagramDesigner.Services;
using ZXing;

namespace AIStudio.Wpf.DiagramDesigner.Additionals.Extensions.ViewModels
{
    public class BarcodeDesignerItemViewModel : DesignerItemViewModelBase
    {
        private IUIVisualizerService visualiserService;

        public BarcodeDesignerItemViewModel() : this(null)
        {

        }

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

        }

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

        }

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

        public override SelectableItemBase GetSerializableObject()
        {
            return new DesignerItemBase(this, Format.ToString());
        }

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

            CustomText = true;

            visualiserService = ApplicationServicesProvider.Instance.Provider.VisualizerService;
        }

        protected override void InitNew()
        {
            base.InitNew();
        }

        protected override void LoadDesignerItemViewModel(SelectableItemBase designerbase)
        {
            base.LoadDesignerItemViewModel(designerbase);

            if (designerbase is DesignerItemBase designer)
            {
                Format = (BarcodeFormat)Enum.Parse(typeof(BarcodeFormat), designer.Reserve.ToString());
            }
        }

        public void AutoSize()
        {
            ItemWidth = 140;
            ItemHeight = 140;
        }

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

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

        public BarcodeFormat Format { get; set; } = BarcodeFormat.QR_CODE;

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

            BarcodeDesignerItemData data = new BarcodeDesignerItemData(this);
            if (visualiserService.ShowDialog(data) == true)
            {
                bool needauto = Text == null;
                Text = data.Text;
                Icon = data.Icon;
                Margin = data.Margin;
                if (needauto)
                {
                    AutoSize();
                }
                return true;
            }

            return false;
        }
    }
}
