private void confirmButton_Click(object sender, EventArgs e)
        {
            string code = codeText.Text;
            try
            {
                Credentials = CompanionAppService.Confirm(Credentials, code);
                Credentials.ToFile();
                CompanionAppService app = new CompanionAppService(Credentials);
                Commander Cmdr = app.Profile();
                Stage3 stage3 = new Stage3(Cmdr.Name);
                stage3.Show();
                this.Hide();

                }
                catch (EliteDangerousCompanionAppAuthenticationException ex)
            {
                Credentials.Clear();
                Credentials.ToFile();
                errorLabel.Text = ex.Message + "\r\nPlease restart this application to re-authenticate";
            }
            catch (EliteDangerousCompanionAppErrorException ex)
            {
                Credentials.Clear();
                Credentials.ToFile();
                errorLabel.Text = ex.Message + "\r\nPlease restart this application to re-authenticate";
            }
            catch (Exception ex)
            {
                Credentials.Clear();
                Credentials.ToFile();
                errorLabel.Text = "Unexpected problem\r\nPlease report this at http://github.com/CmdrMcDonald/EliteDangerousDataProvider/issues\r\n" + ex.Message + "\r\nPlease restart this application to re-authenticate";
            }
        }
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Credentials Credentials = Credentials.FromFile();
            if (Credentials == null || Credentials.appId == null || Credentials.machineId == null || Credentials.machineToken == null)
            {
                Application.Run(new Stage1());
            }
            else
            {
                CompanionAppService app = new CompanionAppService(Credentials);
                Commander Cmdr;
                try
                {
                    Cmdr = app.Profile();
                }
                catch (Exception e)
                {
                    Cmdr = null;
                }

                if (Cmdr == null)
                {
                    // Something wrong with the credentials
                    Credentials.Clear();
                    Credentials.ToFile();
                    Application.Run(new Stage1());
                }
                else
                {
                    // Credentials are good.  Skip straight to stage 3
                    Application.Run(new Stage3(Cmdr.Name));
                }
            }
        }
        public MainWindow()
        {
            InitializeComponent();

            // Configured the EDDI tab
            eddiConfiguration = EDDIConfiguration.FromFile();
            eddiHomeSystemText.Text = eddiConfiguration.HomeSystem;
            eddiHomeStationText.Text = eddiConfiguration.HomeStation;
            eddiInsuranceDecimal.Value = eddiConfiguration.Insurance;

            // Configure the Companion App tab
            CompanionAppCredentials companionAppCredentials = CompanionAppCredentials.FromFile();
            // See if the credentials work
            companionAppService = new CompanionAppService(eddiConfiguration.Debug);
            try
            {
                commander = companionAppService.Profile();
                setUpCompanionAppComplete("Your connection to the companion app is operational, Commander " + commander.Name);
            }
            catch (Exception ex)
            {
                if (companionAppService.CurrentState == CompanionAppService.State.NEEDS_LOGIN)
                {
                    // Fall back to stage 1
                    setUpCompanionAppStage1();
                }
                else if (companionAppService.CurrentState == CompanionAppService.State.NEEDS_CONFIRMATION)
                {
                    // Fall back to stage 2
                    setUpCompanionAppStage2();
                }
            }

            if (commander != null)
            {
                setShipyardFromConfiguration();
            }

            // Configure the NetLog tab
            NetLogConfiguration netLogConfiguration = NetLogConfiguration.FromFile();
            netLogPathTextBox.Text = netLogConfiguration.path;

            // Configure the EDSM tab
            StarMapConfiguration starMapConfiguration = StarMapConfiguration.FromFile();
            edsmApiKeyTextBox.Text = starMapConfiguration.apiKey;
            edsmCommanderNameTextBox.Text = starMapConfiguration.commanderName;

            // Configure the Text-to-speech tab
            SpeechServiceConfiguration speechServiceConfiguration = SpeechServiceConfiguration.FromFile();
            List<String> speechOptions = new List<String>();
            speechOptions.Add("Windows TTS default");
            try
            {
                using (SpeechSynthesizer synth = new SpeechSynthesizer())
                {
                    foreach (InstalledVoice voice in synth.GetInstalledVoices())
                    {
                        if (voice.Enabled)
                        {
                            speechOptions.Add(voice.VoiceInfo.Name);
                        }
                    }
                }

                ttsVoiceDropDown.ItemsSource = speechOptions;
                ttsVoiceDropDown.Text = speechServiceConfiguration.StandardVoice == null ? "Windows TTS default" : speechServiceConfiguration.StandardVoice;
            }
            catch (Exception e)
            {
                using (System.IO.StreamWriter errLog = new System.IO.StreamWriter(Environment.GetEnvironmentVariable("AppData") + @"\EDDI\speech.log", true))
                {
                   errLog.WriteLine("" + System.Threading.Thread.CurrentThread.ManagedThreadId + ": Caught exception " + e);
                }
            }
            ttsRateSlider.Value = speechServiceConfiguration.Rate;
            ttsEffectsLevelSlider.Value = speechServiceConfiguration.EffectsLevel;
            ttsDistortCheckbox.IsChecked = speechServiceConfiguration.DistortOnDamage;

            ttsTestShipDropDown.ItemsSource = ShipDefinitions.ShipModels;
            ttsTestShipDropDown.Text = "Adder";
        }
        /// <summary>
        /// Obtain the EDSM log and sync it with the local datastore
        /// </summary>
        private void edsmObtainLogClicked(object sender, RoutedEventArgs e)
        {
            IEDDIStarSystemRepository starSystemRepository = new EDDIStarSystemSqLiteRepository();
            StarMapConfiguration starMapConfiguration = StarMapConfiguration.FromFile();

            string commanderName;
            if (String.IsNullOrEmpty(starMapConfiguration.commanderName))
            {
                // Fetch the commander name from the companion app
                CompanionAppService companionAppService = new CompanionAppService(eddiConfiguration.Debug);
                Commander cmdr = companionAppService.Profile();
                if (cmdr != null && cmdr.Name != null)
                {
                    commanderName = cmdr.Name;
                }
                else
                {
                    edsmFetchLogsButton.IsEnabled = false;
                    edsmFetchLogsButton.Content = "Companion app not configured and no name supplied; cannot obtain logs";
                    return;
                }
            }
            else
            {
                commanderName = starMapConfiguration.commanderName;
            }

            edsmFetchLogsButton.IsEnabled = false;
            edsmFetchLogsButton.Content = "Obtaining log...";

            StarMapService starMapService = new StarMapService(starMapConfiguration.apiKey, commanderName);

            Dictionary<string, StarMapLogInfo> systems = starMapService.getStarMapLog();
            foreach (string system in systems.Keys)
            {
                EDDIStarSystem CurrentStarSystemData = starSystemRepository.GetEDDIStarSystem(system);
                if (CurrentStarSystemData == null)
                {
                    // We have no record of this system; set it up
                    CurrentStarSystemData = new EDDIStarSystem();
                    CurrentStarSystemData.Name = system;
                    // Due to the potential large number of systems being imported we don't pull individual system data at this time
                }
                CurrentStarSystemData.TotalVisits = systems[system].visits;
                CurrentStarSystemData.LastVisit = systems[system].lastVisit;
                CurrentStarSystemData.PreviousVisit = systems[system].previousVisit;
                starSystemRepository.SaveEDDIStarSystem(CurrentStarSystemData);
            }

            edsmFetchLogsButton.Content = "Log obtained";
        }