// PRE-GENERATED (design session). 자동 전환 규칙 관리 code-behind.
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using DansoriEQ.App.Switching;
using DansoriEQ.Core.Presets;
using DansoriEQ.Core.Switching;

namespace DansoriEQ.App;

public partial class SwitchRulesWindow : Wpf.Ui.Controls.FluentWindow
{
    private List<SwitchRule> _rules;

    public SwitchRulesWindow()
    {
        InitializeComponent();
        _rules = SwitchRulesStore.Load();
        RulesList.ItemsSource = null;
        RulesList.ItemsSource = _rules;

        EnableToggle.IsChecked = AppSettings.Load().AutoSwitchEnabled;

        var lib = new PresetLibrary(AppPaths.PresetsDir);
        PresetCombo.ItemsSource = lib.List();
        if (PresetCombo.Items.Count > 0) PresetCombo.SelectedIndex = 0;
    }

    private void Refresh()
    {
        RulesList.ItemsSource = null;
        RulesList.ItemsSource = _rules;
        SwitchRulesStore.Save(_rules);
    }

    private void Add_Click(object sender, RoutedEventArgs e)
    {
        var match = MatchBox.Text?.Trim();
        var preset = PresetCombo.SelectedItem as string;
        if (string.IsNullOrEmpty(match) || string.IsNullOrEmpty(preset)) return;

        _rules.Add(new SwitchRule
        {
            Trigger = TriggerCombo.SelectedIndex == 1 ? SwitchTrigger.Device : SwitchTrigger.App,
            Match = match,
            PresetName = preset,
            Enabled = true
        });
        MatchBox.Clear();
        Refresh();
    }

    private void Delete_Click(object sender, RoutedEventArgs e)
    {
        if (sender is FrameworkElement fe && fe.Tag is string match)
        {
            var idx = _rules.FindIndex(r => r.Match == match);
            if (idx >= 0) _rules.RemoveAt(idx);
            Refresh();
        }
    }

    private void Enable_Changed(object sender, RoutedEventArgs e)
    {
        var s = AppSettings.Load();
        s.AutoSwitchEnabled = EnableToggle.IsChecked == true;
        s.Save();
    }

    private void Close_Click(object sender, RoutedEventArgs e) => Close();
}
