using GalaSoft.MvvmLight.CommandWpf;
using System.Windows;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using DemoLib.Model;
using DemoLib.Service;
using System;
using UnifiedAutomation.UaBase;

namespace Demo1.ViewModel
{
    public class BusModeViewModel : ViewModelBase
    {
        public BusModeViewModel()
        {
            CloseCommand = new RelayCommand<Window>(CloseCommandExecute);
            SaveCommand = new RelayCommand<Window>(SaveCommandExecute, CanSaveCommand);

            Messenger.Default.Register<Tuple<Reader, NodeId>>(this, (data) =>
            {
                Reader = data.Item1;
                CurrentAntenna = OpcUaService.Instance.GetAntenna(data.Item1);
                SelectedBusHead = CurrentAntenna;
                ActivatedBusHeads = OpcUaService.Instance.GetActivatedBusHeads(data.Item1, data.Item2);

                Messenger.Default.Unregister<Reader>(this);
            });
        }

        #region Close

        public RelayCommand<Window> CloseCommand { get; private set; }

        private void CloseCommandExecute(Window window)
        {
            window.DialogResult = false;
            window.Close();
        }

        #endregion Close

        #region Save

        public RelayCommand<Window> SaveCommand { get; private set; }

        private void SaveCommandExecute(Window window)
        {
            if (OpcUaService.Instance.SetAntenna(Reader, SelectedBusHead))
            {
                window.DialogResult = false;
                window.Close();
            }
        }

        public bool CanSaveCommand(Window window)
        {
            return SelectedBusHead != CurrentAntenna;
        }

        #endregion Save

        private int _selectedBusHead;

        public int SelectedBusHead
        {
            get
            {
                return _selectedBusHead;
            }
            set
            {
                Set(ref _selectedBusHead, value);
            }
        }

        private Reader _reader;

        public Reader Reader
        {
            get => _reader;
            set => Set(ref _reader, value);
        }

        private int _currentAntenna;

        public int CurrentAntenna
        {
            get
            {
                return _currentAntenna;
            }
            set
            {
                Set(ref _currentAntenna, value);
            }
        }

        public int[] _activatedBusHeads;

        public int[] ActivatedBusHeads
        {
            get
            {
                return _activatedBusHeads;
            }
            set
            {
                Set(ref _activatedBusHeads, value);
            }
        }
    }
}