using DragonVideoPlayer;
using System.Diagnostics;
public class EqBand
{
    public double Frequency { get; set; }
    public double Gain { get; set; }
}

public class EqualizerPreset
{
    public List<EqBand> Bands { get; set; } = new List<EqBand>();
}
public class EqualizerForm : Form
{
    private MpvPlayer _player;
    private EqualizerPreset _preset;
    private List<TrackBar> _sliders = new List<TrackBar>();
    private List<Label> _gainLabels = new List<Label>();

    private System.Windows.Forms.Timer _eqTimer;

    private Dictionary<string, double[]> _eqPresets =
        new Dictionary<string, double[]>
    {
        { "Flat",    new double[] { 0,0,0,0,0,0,0,0,0,0 } },
        { "Movie",   new double[] { 4,3,1,0,0,1,2,3,4,4 } },
        { "Sports",  new double[] { 2,2,1,0,1,2,3,3,2,1 } },
        { "Talk",    new double[] { -2,-1,0,1,3,4,4,2,0,-2 } },
        { "Jazz",    new double[] { 2,1,0,0,1,2,2,1,0,0 } },
        { "Classic", new double[] { 3,2,1,0,0,1,2,3,4,5 } },
        { "Rock",    new double[] { 5,3,1,0,1,3,5,4,3,2 } },
        { "重低音", new double[] { 8,7,5,2,0,-1,-2,-2,-3,-3 } },
    };

    public EqualizerForm(MpvPlayer player)
    {
        _player = player;

        Width = 800;
        Height = 450;
        Text = "Audio Equalizer";

        CreateDefaultBands();
        InitializeUI();
        InitializeTimer();
        read_config_file();
    }
    private void InitializeUI()
    {
        Panel bandPanel = new Panel();
        bandPanel.Dock = DockStyle.Top;
        bandPanel.Height = 250;
        Controls.Add(bandPanel);
        this.FormClosing += new FormClosingEventHandler(formClosing);
        int startX = 20;

        for (int i = 0; i < _preset.Bands.Count; i++)
        {
            var band = _preset.Bands[i];

            Panel container = new Panel();
            container.Width = 60;
            container.Height = 220;
            container.Location = new Point(startX + i * 70, 10);
            bandPanel.Controls.Add(container);

            TrackBar slider = new TrackBar();
            slider.Orientation = Orientation.Vertical;
            slider.Minimum = -12;
            slider.Maximum = 12;
            slider.TickStyle = TickStyle.None;
            slider.Height = 150;
            slider.Width = 45;
            slider.Location = new Point(5, 0);
            slider.ValueChanged += Slider_ValueChanged;

            container.Controls.Add(slider);
            _sliders.Add(slider);

            Label gainLabel = new Label();
            gainLabel.Text = "0.0";
            gainLabel.Width = 50;
            gainLabel.Top = 160;
            gainLabel.TextAlign = ContentAlignment.MiddleCenter;
            container.Controls.Add(gainLabel);
            _gainLabels.Add(gainLabel);

            Label freqLabel = new Label();
            freqLabel.Text = band.Frequency.ToString();
            freqLabel.Width = 50;
            freqLabel.Top = 180;
            freqLabel.TextAlign = ContentAlignment.MiddleCenter;
            container.Controls.Add(freqLabel);
        }

        CreatePresetButtons();
    }
    private void CreatePresetButtons()
    {
        FlowLayoutPanel buttonPanel = new FlowLayoutPanel();
        buttonPanel.Dock = DockStyle.Bottom;
        buttonPanel.Height = 60;
        Controls.Add(buttonPanel);

        foreach (var name in _eqPresets.Keys)
        {
            Button btn = new Button();
            btn.Text = name;
            btn.Width = 80;
            btn.Click += (s, e) => ApplyPreset(name);
            buttonPanel.Controls.Add(btn);
        }
    }
    private void InitializeTimer()
    {
        _eqTimer = new System.Windows.Forms.Timer();
        _eqTimer.Interval = 150;
        _eqTimer.Tick += EqTimer_Tick;
    }
    void formClosing(object sender, FormClosingEventArgs e)
    {
        if (config_class.config_bool_read("オーディオイコライザーを保存") == true)
        {
            save_config_file();
        }
    }

    private void read_config_file()
    {



        String eq_data_st = config_class.config_text_read("オーディオイコライザーの値");

        if (string.IsNullOrEmpty(eq_data_st))
            return;
        try
        {

            var values = eq_data_st.Split(',');

            for (int i = 0; i < values.Length && i < _preset.Bands.Count; i++)
            {
                if (double.TryParse(values[i], out double v))
                {
                    _preset.Bands[i].Gain = v;
                    _sliders[i].Value = (int)v;
                    _gainLabels[i].Text = v.ToString("F1");
                }
            }


        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message + ex.StackTrace);
            error.write_error_log(ex.Message + ex.StackTrace);
        }


        ApplyEqualizer();
    }
    private void save_config_file()
    {
        string data = string.Join(",",
    _preset.Bands.Select(b => b.Gain.ToString("F1")));


        config_class.save_config_file("オーディオイコライザーの値", data);



    }

    private void Slider_ValueChanged(object sender, EventArgs e)
    {
        for (int i = 0; i < _sliders.Count; i++)
        {
            _preset.Bands[i].Gain = _sliders[i].Value;
            _gainLabels[i].Text = _sliders[i].Value.ToString("F1");
        }

        _eqTimer.Stop();
        _eqTimer.Start();

    }



    private void EqTimer_Tick(object sender, EventArgs e)
    {
        _eqTimer.Stop();
        ApplyEqualizer();
    }
    private void ApplyEqualizer()
    {
        if (_player == null) return;

        var filters = _preset.Bands
            .Select(b => $"equalizer=f={b.Frequency}:g={b.Gain:F1}");

        string filterChain = string.Join(",", filters);

        Debug.WriteLine(filterChain);
        _player.SendToMpv($"{{\"command\": [\"af\", \"set\", \"{filterChain}\"]}}");

        // _mpv.Command("af", "set", filterChain);
    }
    private void ApplyPreset(string name)
    {
        if (!_eqPresets.ContainsKey(name)) return;

        var values = _eqPresets[name];

        for (int i = 0; i < values.Length; i++)
        {
            _preset.Bands[i].Gain = values[i];
            _sliders[i].Value = (int)values[i];
        }

        ApplyEqualizer();
    }
    private void CreateDefaultBands()
    {
        double[] freqs =
        { 31, 62, 125, 250, 500, 1000, 2000, 4000, 8000, 16000 };

        _preset = new EqualizerPreset();

        foreach (var f in freqs)
        {
            _preset.Bands.Add(new EqBand
            {
                Frequency = f,
                Gain = 0
            });
        }
    }
}