using System;
using System.Linq;
using System.Net;
using System.Security;
using System.Windows;
using Ecng.Common;
using MoreLinq;
using StockSharp.Algo;
using StockSharp.Algo.Testing;
using StockSharp.BusinessEntities;
using StockSharp.Logging;
using StockSharp.Messages;
using StockSharp.Quik;

namespace Test
{
    public partial class MainWindow : Window
    {
        public Connector Trader; 

        public MainWindow()
        {
            InitializeComponent();
        }

        private QuikTrader RealQuikConnector()
        {
            var _qtrader = new QuikTrader
            {
                LuaLogin = "quik",
                LuaFixServerAddress = "127.0.0.1:5001".To<EndPoint>(),
                LuaPassword = "quik".To<SecureString>()
            };
            return _qtrader;
        }

        private RealTimeEmulationTrader<IMessageAdapter> EmulationQuikConnector()
        {
            var _tMessageAdapter = new QuikTrader
            {
                LuaFixServerAddress = "127.0.0.1:5001".To<EndPoint>(),
                LuaLogin = "quik",
                LuaPassword = "quik".To<SecureString>(),
                LogLevel = LogLevels.Debug,
                UpdateSecurityByLevel1 = true
            }.MarketDataAdapter;

            var portfolio = new Portfolio {Name = "Симулятор", BeginValue = 100000};
            var _trader = new RealTimeEmulationTrader<IMessageAdapter>(_tMessageAdapter, portfolio);

            return _trader;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (Trader == null)
            {
                Trader = RealQuikConnector();
                //Trader = EmulationQuikConnector();

                Trader.NewSecurities += securities =>
                {
                    securities.ForEach(s =>
                    {
                        try
                        {
                            if (s.Id == "SBER@TQBR" || s.Id == "SBER@QJSIM") //
                            {
                                Trader.RegisterMarketDepth(s);
                                Trader.RegisterSecurity(s);
                                Trader.RegisterTrades(s);
                                Console.WriteLine(@"{0} - зарегестрирован, все ок", s);
                            }

                            if (s.Id == "RIM8@FORTS") //
                            {
                                Trader.RegisterMarketDepth(s);
                                Trader.RegisterSecurity(s);
                                Trader.RegisterTrades(s);
                                Console.WriteLine(@"{0} - зарегестрирован, все ок", s);
                            }
                        }
                        catch (Exception exc)
                        {
                            Console.WriteLine(exc.Message, @" Ошибка регистрации ", s);
                            throw;
                        }
                    });
                };

                Trader.NewPortfolio += portfolio => { Console.WriteLine(@"Получен портфель - {0}", portfolio.Name); };
                Trader.NewTrades += a => { Console.WriteLine(@"Событие NewTrades"); };


                Trader.ValuesChanged += (sec, b, c, d) =>
                {
                    Console.Write(@"Событие ValuesChanged ");
                    if (sec.LastTrade != null)
                        Console.WriteLine(@"LastTrade.Price={0} AsksCount={1}", sec.LastTrade.Price, sec.AsksCount);
                    else
                        Console.WriteLine(@"LastTrade.Price=null");
                };

                Trader.SecuritiesChanged += sec =>
                {
                    Console.Write(@"Событие SecuritiesChanged");
                    if (sec.Last().LastTrade != null)
                        Console.WriteLine(@"LastTrade.Price={0} AsksCount={1}", sec.Last().LastTrade.Price,
                            sec.Last().AsksCount);
                    else
                        Console.WriteLine(@"LastTrade.Price=null");
                };
            }

            Trader.Connect();
        }
    }
}