using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using System.Linq;
using tiron_demo.Context;
using tiron_demo.Models;

namespace tiron_demo;

public partial class AddPartner : Window
{
    private short _ratingBackup;
    private Partner _partner;

    public AddPartner()
    {
        InitializeComponent();

        _partner = new Partner();
        _ratingBackup = 0;

        PartnerTypeComboBox.ItemsSource = Helper.context.PartnerTypes;
        PartnerPanel.DataContext = _partner;
    }

    public AddPartner(Partner partner)
    {
        InitializeComponent();

        _partner = partner;
        _ratingBackup = partner.Rating;

        PartnerTypeComboBox.ItemsSource = Helper.context.PartnerTypes;
        PartnerPanel.DataContext = _partner;
    }

    private void Button_Click_Back(object? sender, RoutedEventArgs args)
    {
        _partner.Rating = _ratingBackup;

        PartnersWindow partnersWindow = new PartnersWindow();
        partnersWindow.Show();
        Close();
    }

    private void Button_Click_Save(object? sender, RoutedEventArgs args)
    {
        if (_partner.Rating >= 0)
        {
            if (_partner.Id == 0)
            {
                Helper.context.Partners.Add(_partner);
                Helper.context.SaveChanges();
            }
            else
            {
                Helper.context.Partners.Update(_partner);
                Helper.context.SaveChanges();
            }

            PartnersWindow partnersWindow = new PartnersWindow();
            partnersWindow.Show();
            Close();
        }
    }
}