using SewerStammGen.DAL.Services.PostgresqlData;
using SewerStammGen.Shared.Contracts;
using SewerStammGen.Shared.Domain;
using StammGenerator.Commands;
using StammGenerator.Interface;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Input;

namespace StammGenerator.ViewModel
{
    public class ProjektListViewModel : BaseViewModel
    {
        private IProjektDataService genericDataService;
        private readonly ObservableCollection<Projekt> _projekte;
        private readonly IActualState _actualState;
        public ObservableCollection<Projekt> Projekte {  get => _projekte; }
        public bool CanSelectProjekt => _selectedProjekt != null;

        public ICommand SelectCommand { get; set; }
        public ICommand AddCommand { get; set; }
        public ICommand EditCommand { get; set; }

        private Projekt? _selectedProjekt;
        public ICommand SchachtImportCommand { get; set; }
        public ICommand DatenExportCommand { get; set; }


        public Projekt? SelectedProjekt
        {
            get => _selectedProjekt;
            set
            {
                if(_selectedProjekt != value)
                {
                    _selectedProjekt = value;
                    OnPropertyChanged();
                    OnPropertyChanged(nameof(CanSelectProjekt));
                }
            }
        }

        public ProjektListViewModel(IProjektDataService generic, IHaltungDataService haltungDataService, ISchachtDataService schachtDataService, IActualState actualState, IRenavigator renavigator, IRenavigator navigatetoImport)
        {
            _projekte = new ObservableCollection<Projekt>();
            if (generic == null) throw new ArgumentNullException(nameof(generic));
            this.genericDataService = generic;
            _actualState = actualState;
            AddCommand = new ProjektAddCommand(generic,actualState, renavigator);
            SelectCommand = new ProjektSelectCommand(actualState,this);
            EditCommand = new ProjektEditCommand(generic, actualState, renavigator, this);

            LoadProjekte();

            SchachtImportCommand = new RelayCommand((x) =>
            {
                navigatetoImport.Renavigate();
            });
            DatenExportCommand = new ProjectExportCommand(this, haltungDataService, schachtDataService);
        }

        private async void LoadProjekte()
        {
            var projects = await genericDataService.GetAll();

            InitCollection(_projekte, projects);
            
        }

        private void InitCollection(ObservableCollection<Projekt> projekte, IEnumerable<Projekt> projects)
        {
            projekte.Clear();
            foreach(var i in projects)
            {
                projekte.Add(i);
            }
        }
    }
}
