using System;
using Xamarin.Forms;
using Navigator.Services;
using Navigator.Views;
using MarketData.Service;
using Navigator.Utils;

namespace Navigator
{
    public partial class App : Application
    {

        public App()
        {
          InitializeComponent();
          DependencyService.Register<MockDataStore>();
          InitializeConnection();

          MainPage = new MainPage();
        }

        private void InitializeConnection()
        {
          String ipAddress=IPCache.GetIPAddress();
          if (null != ipAddress && MarketDataServiceClient.GetInstance().Ping(ToUrl(ipAddress)))
          {
            MarketDataServiceClient.GetInstance().SetUrl(ToUrl(ipAddress), AppSettingsManager.Settings["ServiceUser"]);
          }
          else if (MarketDataServiceClient.IsWiFiNetwork() && MarketDataServiceClient.GetInstance().Ping(ToUrl(AppSettingsManager.Settings["Service_Local"])))
          {
            IPCache.SaveIPAddress(AppSettingsManager.Settings["Service_Local"]);
            MarketDataServiceClient.GetInstance().SetUrl(ToUrl(AppSettingsManager.Settings["Service_Local"]), AppSettingsManager.Settings["ServiceUser"]);
          }
          else if (MarketDataServiceClient.GetInstance().Ping(ToUrl(AppSettingsManager.Settings["Service_Network"])))
          {
            IPCache.SaveIPAddress(AppSettingsManager.Settings["Service_Network"]);
            MarketDataServiceClient.GetInstance().SetUrl(ToUrl(AppSettingsManager.Settings["Service_Network"]), AppSettingsManager.Settings["ServiceUser"]);
          }
        }

        private String ToUrl(String ipAddress)
        {
          return AppSettingsManager.Settings["Service_Prefix"] + ipAddress + AppSettingsManager.Settings["Service_Postfix"];
        }

        protected override void OnStart()
        {
        }

        protected override void OnSleep()
        {
        }

        protected override void OnResume()
        {
        }
    }
}
