using MYOB.AccountRight.SDK.Contracts;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace InABox.Poster.MYOB;
/// 
/// Interaction logic for MYOBCompanyFileSelectionDialog.xaml
/// 
public partial class MYOBCompanyFileSelectionDialog : Window, INotifyPropertyChanged
{
    private bool _canSave;
    public bool CanSave
    {
        get => _canSave;
        set
        {
            _canSave = true;
            OnPropertyChanged();
        }
    }
    public List Items
    {
        get => Grid.Items;
        set => Grid.Items = value;
    }
    public MYOBCompanyFile? Result
    {
        get
        {
            var row = Grid.SelectedRows.FirstOrDefault();
            if(row is not null)
            {
                return Grid.LoadItem(row);
            }
            return null;
        }
    }
    public MYOBCompanyFileSelectionDialog()
    {
        InitializeComponent();
    }
    public event PropertyChangedEventHandler? PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    private void Grid_OnSelectItem(object sender, DynamicGrid.DynamicGridSelectionEventArgs e)
    {
        CanSave = e.Rows is not null && e.Rows.Length > 0;
    }
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        Grid.Refresh(true, true);
    }
    private void CancelButton_Click(object sender, RoutedEventArgs e)
    {
        DialogResult = false;
        Close();
    }
    private void OKButton_Click(object sender, RoutedEventArgs e)
    {
        DialogResult = true;
        Close();
    }
    public static CompanyFile? SelectCompanyFile()
    {
        var data = MYOBPosterEngine.GetConnectionData();
        var window = new MYOBCompanyFileSelectionDialog();
        var files = data.CompanyFileService.GetRange();
        window.Items = files.Select(x =>
        {
            return new MYOBCompanyFile
            {
                ID = x.Id,
                Name = x.Name
            };
        }).ToList();
        if(window.ShowDialog() == true)
        {
            var result = window.Result;
            if(result is not null)
            {
                return files.FirstOrDefault(x => x.Id == result.ID);
            }
            else
            {
                return null;
            }
        }
        else
        {
            return null;
        }
    }
}