using qtc_net_client_2.Services;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace qtc_net_client_2.Forms
{
    public partial class TokenJackpotSpinner : Form
    {
        public int TokensWon { get; private set; }

        private bool AllowClose = false;
        private AudioService _audioService = new();
        public TokenJackpotSpinner()
        {
            InitializeComponent();
        }

        private async void TokenJackpotSpinner_Load(object sender, EventArgs e)
        {
            btnClaim.Enabled = false;
            AllowClose = false;
            await StartSpinAnimation(lblTokensWon);
        }

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

        private void TokenJackpotSpinner_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!AllowClose) e.Cancel = true;
        }

        private void btnClaim_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.OK;
            Close();
        }

        public async Task StartSpinAnimation(Label label)
        {
            if (label.IsHandleCreated)
            {
                Random rnd = new Random();
                _audioService.PlaySoundEffect("sndTokenSpinLoop");

                while (_audioService.OutputDevice?.PlaybackState == NAudio.Wave.PlaybackState.Playing)
                {
                    label.BeginInvoke(delegate () { label.Text = $"{rnd.Next(0, 300)} Tokens Won"; });
                    await Task.Delay(10);
                }

                var win = rnd.Next(0, 300);

                label.BeginInvoke(delegate ()
                {
                    label.Text = $"{win} Tokens Won";
                    btnClaim.Enabled = true;
                    _audioService.PlaySoundEffect("sndTokenWin");
                });

                _audioService.Dispose();
                AllowClose = true;
                TokensWon = win;
            }
        }
    }
}
