using qtcnet_client.Services;
using System;
using System.ComponentModel;
using System.Windows.Forms;

namespace qtcnet_client.Forms
{
    public partial class JackpotSpinForm : Form
    {
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public int CurrencyWon { get; set; } = 0;

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public double AnimationLengthMilliseconds { get; set; } = 1500;

        private readonly System.Windows.Forms.Timer _animationTimer;
        private readonly System.Windows.Forms.Timer _stopTimer;
        private readonly Random _rndInt = new();
        private bool _allowClose = true;

        private readonly AudioService _audioService;
        public JackpotSpinForm(AudioService audioService)
        {
            _audioService = audioService;
            InitializeComponent();
            FormClosing += JackpotSpinForm_FormClosing;

            _animationTimer = new()
            {
                Interval = 20
            };
            _animationTimer.Tick += AnimationTimer_Tick;

            _stopTimer = new();
            _stopTimer.Tick += StopTimer_Tick;
        }

        private void JackpotSpinForm_Load(object sender, EventArgs e)
        {
            ExecuteAnimation();
        }

        private void JackpotSpinForm_FormClosing(object? sender, FormClosingEventArgs e)
        {
            if (!_allowClose)
                e.Cancel = true;
        }

        private void JackpotSpinForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            DialogResult = DialogResult.OK;
        }

        private void ExecuteAnimation()
        {
            DoubleBuffered = true;
            _allowClose = false;

            // Start spinning numbers
            _animationTimer.Start();
            _audioService.PlaySoundEffect("sndTokenSpinLoop");

            // Schedule stop
            _stopTimer.Interval = (int)AnimationLengthMilliseconds;
            _stopTimer.Start();
        }

        private void AnimationTimer_Tick(object? sender, EventArgs e)
        {
            if (!IsHandleCreated && IsDisposed)
                return;

            lblSpinAnim.Text = $"{_rndInt.Next(999)} Q's Won";
        }

        private void StopTimer_Tick(object? sender, EventArgs e)
        {
            _stopTimer.Stop();
            _animationTimer.Stop();

            // Show final result
            lblSpinAnim.Text = $"{CurrencyWon} Q's Won";

            // play done sound
            _audioService.PlaySoundEffect("sndTokenWin");

            _allowClose = true;
        }
    }
}