using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using SlnMesnac.Model.domain;
using SlnMesnac.Repository.service;
using SlnMesnac.WPF.ViewModel.Base;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using SlnMesnac.Common;
using SlnMesnac.WPF.Attribute;
using Prism.Events;
using SlnMesnac.WPF.Event;
using Microsoft.Extensions.DependencyInjection;

namespace SlnMesnac.WPF.ViewModel
{
    [RegisterAsSingletonAttribute]
    public partial class ProductInfoViewModel : BaseViewModel
    {

        private readonly Ibase_product_infoServices _services;

        private readonly IEventAggregator _eventAggregator;

        [ObservableProperty]
        public string productCodeStr = string.Empty;

        [ObservableProperty]
        public string productNameStr = string.Empty;


        [ObservableProperty]
        public ObservableCollection<base_product_info> productInfoItems = new ObservableCollection<base_product_info>();

        public ProductInfoViewModel(Ibase_product_infoServices services, IEventAggregator eventAggregator)
        {
            _services = services;

            _eventAggregator = eventAggregator;

            QueryProductInfo();
        }

        [RelayCommand]
        private void QueryProductInfo()
        {
            Expression<Func<base_product_info, bool>> exp = s1 => true;

            if(!string.IsNullOrEmpty(productCodeStr))
            {
                exp = exp.And(x => x.productCode == productCodeStr);
            }

            if (!string.IsNullOrEmpty(productNameStr))
            {
                exp = exp.And(x=>x.productName == productNameStr);
            }

            var infos = _services.Query(exp);

            ProductInfoItems = new ObservableCollection<base_product_info>(infos);
        }

        [RelayCommand]
        private void EditProductInfo(string productCode)
        {
            var info = _services.Query(x=>x.productCode == productCode).First();

            _eventAggregator.GetEvent<ProductInfoEvent>().Publish(info);

            var mainWindow = App.ServiceProvider.GetService<MainWindowViewModel>();
            mainWindow.ControlOnClick("EditDetails");
        }
    }
}
