using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

using Betfair.Gamex.API;
using Betfair.Gamex.API.Entities;

namespace Betfair.Gamex.API.UberClient
{
    /// <summary>
    /// Updates game data from the API and applies to game display
    /// </summary>
    class GameUpdateThread
    {
        private Adapter m_Adapter;
        private long m_ChannelId;
        private MainForm m_MainForm;

        /// <summary>
        /// Constructor
        /// </summary>
        public GameUpdateThread(Adapter adapter, long channelId, MainForm mainForm)
        {
            m_Adapter = adapter;
            m_ChannelId = channelId;
            m_MainForm = mainForm;
        }

        /// <summary>
        /// Run the main update thread
        /// </summary>
        public void Run()
        {
            while (true)
            {
                // call into main form to update data
                channelSnapshot snapshot = null;
                try
                {
                    snapshot = m_Adapter.GetChannelSnapshot(m_ChannelId);
                    if (snapshot == null || snapshot.channel == null || snapshot.channel.game == null || snapshot.channel.game.markets == null || snapshot.channel.game.markets.market == null || snapshot.channel.game.markets.market.Length == 0 || snapshot.channel.game.markets.market[0].selections == null || snapshot.channel.game.markets.market[0].selections.selection == null || snapshot.channel.game.markets.market[0].selections.selection.Length == 0)
                    {
                        continue;
                    }

                    m_MainForm.UpdateGameData(snapshot);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    continue;
                }

                if (snapshot.channel.game.markets.market[0].status == marketStatusEnum.ACTIVE)
                {
                    // delay 2 seconds between each update
                    Thread.Sleep(2000);
                }
                else
                {
                    // delay 1 second between each update during suspend so round starts more "on time"
                    Thread.Sleep(1000);
                }
            }
        }
    }
}
