using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Windows.Input;
using ZXing;

namespace Borepin.DialogModel
{
    public class ScanDialogModel : BindableBase, IDialogAware
    {
        #region Private Fields
        private object _Instance;
        #endregion

        #region Constructors
        public ScanDialogModel()
        {
            AbortCommand = new DelegateCommand(AbortCommandExecute);
            ScannedCommand = new DelegateCommand(ScannedCommandExecute);

            IsVisible = true;
            IsScanning = true;
        }
        #endregion

        #region Fields
        public event Action<IDialogParameters> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        private Result _ScanResult;
        public Result ScanResult
        {
            get => _ScanResult;
            set => SetProperty(ref _ScanResult, value);
        }

        private bool _IsScanning;
        public bool IsScanning
        {
            get => _IsScanning;
            set => SetProperty(ref _IsScanning, value);
        }

        private bool _IsVisible;
        public bool IsVisible
        {
            get => _IsVisible;
            set => SetProperty(ref _IsVisible, value);
        }
        #endregion

        #region Commands
        private ICommand _ScannedCommand;

        public ICommand ScannedCommand
        {
            get => _ScannedCommand;
            set => SetProperty(ref _ScannedCommand, value);
        }
        public void ScannedCommandExecute()
        {
            IsScanning = false;
            IsVisible = false;

            IDialogParameters parameters = new DialogParameters()
            {
                { "result", "scanned" },
                { "value", ScanResult.Text },
                { "instance", _Instance },
            };
            RequestClose(parameters);
        }

        private ICommand _AbortCommand;
        public ICommand AbortCommand
        {
            get => _AbortCommand;
            set => SetProperty(ref _AbortCommand, value);
        }
        public void AbortCommandExecute()
        {
            IsScanning = false;
            IsVisible = false;
            
            IDialogParameters parameters = new DialogParameters()
            {
                { "result", "abort" },
                { "instance", _Instance },
            };
            RequestClose(parameters);
        }
        #endregion

        #region IDialogAware
        public void OnDialogClosed()
        {

        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            _Instance = parameters.GetValue<object>("instance");
        }
        #endregion
    }
}
