using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Deployment.Application;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Reflection;
using System.ServiceModel;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Navigation;
using System.Windows.Threading;

using BS.Shared;
using BS.Shared.Extensions;

using BeWo.Core;
using BeWo.ServiceProxy;
using BeWo.View;
using BeWo.View.Detail;
using Path = System.IO.Path;

namespace BeWo
{
    /// <summary>
    /// Interaktionslogik für LoginControl.xaml
    /// </summary>
    public partial class LoginControl : UserControl, INotifyPropertyChanged
    {
        private readonly Stack<Control> _ModalPopUpControls = new Stack<Control>();

        private bool _IsTechSupport;
        public bool IsTechSupport
        {
            get { return _IsTechSupport; }
            set { _IsTechSupport = value; OnPropertyChanged("IsTechSupport"); }
        }

        private Control _CurrentModalPopUp;

        private Grid _ModalPopUpBackGround;

        private readonly string _ProfilesFilePath;

        public event EventHandler LoginSuccessful;


        //proxy anmeldedaten
        public string proxyname;
        public string proxyUsername;
        public string proxypasswd; 

        private List<BeWoProfile> _ProfileList;
        public List<BeWoProfile> ProfileList
        {
            get { return _ProfileList; }
            set { _ProfileList = value; }
        }

        public LoginControl()
        {

            InitializeComponent();
			var checkPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\profiles.txt";
			if (File.Exists(checkPath))
			{
				//Nimm lokalen Profilpfad wenn er existiert. Wird z.B. bei Kunden mit Citrix Server genutzt, die keine Clickonce Installation vornehmen
				_ProfilesFilePath = checkPath;
			}
			else
			{
				_ProfilesFilePath = Path.Combine(BeWoApp.GetAndCreateUserAppDataPath(), "profiles.txt");
			}
			
	        ProfileList = new List<BeWoProfile>();
	        BeWoProfile selectedProfile = null;
            HeightFrom = gridLogin.Height;
            HeightTo = gridLogin.Height + 64;
            LineYCoordFrom = linkLine.Y1;
            LineYCoordTo = linkLine.Y1 + 64;

            DataContext = this;

            ReadProxyName();

            try
            {
	            ReadProfileList();
               
#if DEBUG


				var uri = new Uri("https://localhost/Host/?k=demo&s=localhost/service");

				var paramDic = BeWoUtils.ParseQuery(uri.Query);
				string v1, v2;
				paramDic.TryGetValue("k", out v1);
				paramDic.TryGetValue("s", out v2);
				BeWoApp.Tenant = v1;
				BeWoApp.ServerName = v2;
				if (ProfileList.Count > 0)
					ProfileList.Insert(0, new BeWoProfile(v1, v2, BeWoApp.Tenant));
				else
					ProfileList.Add(new BeWoProfile(v1, v2, BeWoApp.Tenant));
				SaveProfileListToFile();

			


#else
				if (ApplicationDeployment.IsNetworkDeployed && ApplicationDeployment.CurrentDeployment.ActivationUri != null)
                {
                    //Start über IE
                    //MessageBox.Show(String.Format("Start über IE.\nActivationUri: {0}\nUpdateLocation: {1}", ApplicationDeployment.CurrentDeployment.ActivationUri, ApplicationDeployment.CurrentDeployment.UpdateLocation));
                    BeWoProfile p = GenerateProfileFromUri(ApplicationDeployment.CurrentDeployment.ActivationUri);
					if (!String.IsNullOrEmpty(p.Tenant) && !String.IsNullOrEmpty(p.Server))
					{
						BeWoApp.Tenant = p.Tenant;

						if (ProfileList.Count > 0)
						{
							selectedProfile = ProfileList.Find(ip => ip.Tenant == p.Tenant);
						}
						if (selectedProfile == null)
						{
							if (ProfileList.Count > 0)
								ProfileList.Insert(0, p);
							else
								ProfileList.Add(p);
						} 
						else
						{
							ProfileList.Remove(selectedProfile);
							selectedProfile.Server = p.Server;
							ProfileList.Insert(0, selectedProfile);
						}
						SaveProfileListToFile();
					}
					else if (!String.IsNullOrEmpty(p.Tenant) && p.Tenant.ToLower() == "demo")
					{
						p.Server = "1";
						ProfileList.Add(p);
					}

                }
                else
                {
                    //MessageBox.Show(String.Format("Start über Firefox oder über installiertes Desktop Icon.\nActivationUri: {0}\nUpdateLocation: {1}", ApplicationDeployment.CurrentDeployment.ActivationUri, ApplicationDeployment.CurrentDeployment.UpdateLocation));
                   
                }
#endif
			}
            catch (Exception ex)
            {
                
            }

			
			if (ProfileList.Count == 0 || String.IsNullOrEmpty(ProfileList[0].Tenant))
			{
				//LH Würzburg Hack:
				if (ApplicationDeployment.IsNetworkDeployed)
				{
					Uri uri = ApplicationDeployment.CurrentDeployment.ActivationUri;
					if (uri == null)
					{
						uri = ApplicationDeployment.CurrentDeployment.UpdateLocation;
					}
					if (uri != null)
					{
						if (uri.Host.IndexOf("10.0.116.4") >= 0 || uri.Host.IndexOf("lebenshilfe-wuerzburg") >= 0)
						{
							BeWoProfile bp = new BeWoProfile("Lebenshilfe Würzburg", "10.0.116.4", "1");
							ProfileList.Add(bp);
							SaveProfileListToFile();
						}
						else if (uri.Host.IndexOf("fortis") >= 0)
						{
							BeWoProfile bp = new BeWoProfile("Fortis", "FOBP01.fortis-ev.org.local", "4526293996");
							ProfileList.Add(bp);
							SaveProfileListToFile();
						}
					}
				}

			}

            // IP-Adresse holen
	        try
	        {
				var wc = new WebClient();
				var adminUrl = GetAdminUrl();
				if (!String.IsNullOrEmpty(adminUrl))
				{
					Uri path = new Uri(GetAdminUrl());

					BeWoApp.IpAddress = Encoding.UTF8.GetString(wc.DownloadData(path));
				}
	        }
	        catch (Exception)
	        {

				BeWoApp.IpAddress = String.Empty;
	        }
			
	        //string ipaddress = "";

#if DEBUG
            IsTechSupport = true;
#else
			IsTechSupport = !String.IsNullOrEmpty(BeWoApp.IpAddress) && BeWoApp.IpAddress.Equals("87.79.89.65");
#endif
			// --------------

            if (ProfileList.Count == 0 || String.IsNullOrEmpty(ProfileList[0].Tenant))
				ShowEnterTenantDialog();

            //if (ProfileList.Count == 0)
                //ProfileList.Add(new BeWoProfile("Ungültiges Profil", "Bitte geben Sie hier einen gültigen Server an. Z.B. app1", "Kundennummer"));
	        BeWoProfile firstProfile = null;
			if (ProfileList.Count > 0)
				firstProfile = ProfileList[0];
			ProfileList.Sort((a, b) => a.Name.CompareTo(b.Name));
	        profileSelectionComboBox.ItemsSource = ProfileList;

			selectedProfile = profileSelectionComboBox.SelectedItem as BeWoProfile;
            if (selectedProfile == null && ProfileList.Count > 0)
				selectedProfile = firstProfile;
            
            if (profileSelectionComboBox.SelectedItem == null)
                profileSelectionComboBox.SelectedItem = selectedProfile;

			if (selectedProfile != null && selectedProfile.Tenant == "demo")
            {
                TextBox_Username.Text = "demo";
                PasswordBox_Password.Password = "demo";
                button_login.Focus();
            }
            else
            {
                TextBox_Username.Focus();
            }

            //this.lblTenant.Content = BeWoApp.Tenant;
            lblVersion.Content = BeWoApp.Version;

            Loaded += LoginControl_Loaded;

            if (!IsTechSupport) 
                return;

            linkLine.Margin = new Thickness(linkLine.Margin.Left, linkLine.Margin.Top + 25, linkLine.Margin.Right, linkLine.Margin.Bottom);
            gridLogin.Height += 25;
        }

		private void ReadProfileList()
		{
			if (File.Exists(_ProfilesFilePath))
			{
				var myFile = new StreamReader(_ProfilesFilePath, Encoding.Default);

				while (!myFile.EndOfStream)
				{
					var data = myFile.ReadLine().Split('|');

					if (data.Length >= 3)
					{
						if (!String.IsNullOrEmpty(data[1]) && !String.IsNullOrEmpty(data[2]))
							ProfileList.Add(new BeWoProfile(data[0], data[1], data[2]));
					}
				}
				myFile.Close();
			}
		}

		private string GetNumericServerName(string serverName)
		{
			if (!String.IsNullOrEmpty(serverName))
			{
				int snOut = 0;
				if (!Int32.TryParse(serverName, out snOut))
				{
					String nname = serverName.Replace("app", "");
					if (nname.IndexOf('.') > 0)
					{
						return nname.Substring(0, nname.IndexOf('.'));
					}
				}
			}
			return serverName;
		}

        private void ShowEnterTenantDialog()
        {
            BeWoProfile p = null;
            
            var cancel = false;
            var tenant = String.Empty;
            while (p == null && !cancel)
            {
                var dlg = new EnterTenantDialog {Tenant = tenant};
                var result = dlg.ShowDialog();
                if (result.HasValue && result.Value)
                {
                    tenant = dlg.Tenant;
					var server = GetServerFromTenant(tenant);
                    if (!String.IsNullOrEmpty(server))
                    {
                        p = new BeWoProfile(tenant, server, tenant);
						if (ProfileList.Count > 0)
							ProfileList.Insert(0, p);
						else
							ProfileList.Add(p);
                        SaveProfileListToFile();
                    }
                    else
                    {
                        MessageBox.Show("Unbekannte Kundennummer '" + tenant + "'", "BeWoPlaner");
                    }
                }
                else
                {
                    cancel = true;
                }
            }
        }

        private string GetServerFromTenantAlt(string tenant)
        {
	        try
	        {
		        using (WebClient client = new WebClient())
		        {
			        //MessageBox.Show(hostAddress);
			        byte[] response = client.UploadValues(GetAdminUrl(), "POST", new NameValueCollection()
			        {
				        {"k", tenant},
				        {"p", "6ca793d9e460"}
			        });

			        String server = System.Text.Encoding.ASCII.GetString(response);

			        return server;
		        }
	        }
	        catch (Exception ex)
	        {
		        MessageBox.Show(String.Format("Fehler beim Prüfen der Kundennummer: {0}\n\n{1}", ex.Message, ex.StackTrace));
	        }

	        return null;
        }

		private string GetServerFromTenant(string tenant)
		{
			try
			{
				if (tenant == "demo")
				{
					return "app1.bewoplaner.de";
				}
//Server URL über Kundennummer:
//https://bewoplaner.beyondsoft.de/getserver.php?CustomerID=1234567890

//Lizenzstatus über Kundennummer (Lizenzzahlen und aktivierte Module)
//Nur Testdaten. Weiß gar nicht mehr so genau wofür das gut war…
//https://bewoplaner.beyondsoft.de/getcontractstate.php?CustomerID=1234567890

				String url = String.Format("https://bewoplaner.beyondsoft.de/getserver.php?CustomerID={0}", tenant);
				using (WebClient client = new WebClient())
				{
					//MessageBox.Show(hostAddress);
					byte[] response = client.UploadValues(url, "POST", new NameValueCollection());

					String server = System.Text.Encoding.ASCII.GetString(response);

					return server;
				}
			}
			catch (Exception ex)
			{
				//MessageBox.Show(String.Format("Fehler beim Prüfen der Kundennummer: {0}\n\n{1}", ex.Message, ex.StackTrace));
				return null;
			}

			return null;
		}

	    private string GetAdminUrl()
	    {
		    String address = String.Empty;

#if DEBUG
		    if (true)
		    {
			    address = "http://localhost/Host";

			    //Uri uri = new Uri("http://app.beyondsoft.de/bewo.application");
			    //hostAddress = String.Format("{0}://{1}", uri.Scheme, uri.Host);
#else
            if (ApplicationDeployment.IsNetworkDeployed && ApplicationDeployment.CurrentDeployment.UpdateLocation != null)
            {
	            Uri uri = ApplicationDeployment.CurrentDeployment.UpdateLocation;
	            address = String.Format("{0}://{1}", uri.Scheme, uri.Host);
#endif

		    }
		    if (String.IsNullOrEmpty(address))
		    {
			    return null;
		    }

		    return String.Format("{0}/{1}", address, "Admin.aspx");
	    }

		
        private BeWoProfile GenerateProfileFromUri(Uri uri)
        {

            var paramDic = BeWoUtils.ParseQuery(uri.Query);
            string v1, v2;

            paramDic.TryGetValue("k", out v1);
            paramDic.TryGetValue("s", out v2);
            //if (String.IsNullOrEmpty(v1))
            //{
            //    v1 = "demo";
            //}

            //if (String.IsNullOrEmpty(v2))
            //{
            //    v2 = "Ungültiger Server";
            //    String uriStr = uri.ToString();
            //    if (!String.IsNullOrEmpty(uriStr))
            //    {
            //        v2 = uriStr;
            //        if (uriStr.IndexOf("://") >= 0)
            //            v2 = uriStr.Substring(uriStr.IndexOf("://") + 3);
            //        if (v2.ToLower().IndexOf("/bewo.application") > 0)
            //            v2 = v2.Substring(0, v2.ToLower().IndexOf("/bewo.application"));
            //    }
            //}

            return new BeWoProfile(v1, v2, v1);
        }

        public void CloseCurrentPopUp()
        {
            if (this._ModalPopUpBackGround != null)
            {
                this.Dispatcher.BeginInvoke(
                    DispatcherPriority.Normal,
                    (Action)delegate
                        {
                            this.grid_root.Children.Remove(this._CurrentModalPopUp);
                            this._CurrentModalPopUp = null;
                            if (this._ModalPopUpControls.Count == 0)
                            {
                                this.grid_root.Children.Remove(this._ModalPopUpBackGround);
                                this._ModalPopUpBackGround = null;
                            }
                            else
                            {
                                var control = this._ModalPopUpControls.Pop();
                                this._CurrentModalPopUp = control;
                                this.grid_root.Children.Add(control);
                                Panel.SetZIndex(control, int.MaxValue);
                            }
                        });
            }
        }

        public void ShowControlAsModalPopUp(Control control)
        {
            this.ShowControlAsModalPopUp(control, HorizontalAlignment.Center, VerticalAlignment.Center);
        }

        public void ShowControlAsModalPopUp(Control control, HorizontalAlignment ha, VerticalAlignment va)
        {
            this.Dispatcher.BeginInvoke(
                DispatcherPriority.Normal,
                (Action)delegate
                    {
                        if (this._CurrentModalPopUp != null)
                        {
                            this.grid_root.Children.Remove(this._CurrentModalPopUp);
                            this._ModalPopUpControls.Push(this._CurrentModalPopUp);
                        }
                        else
                        {
                            this.ShowModalBackground();
                        }

                        this._CurrentModalPopUp = control;
                        control.HorizontalAlignment = ha;
                        control.VerticalAlignment = va;
                        Grid.SetColumnSpan(control, 3);
                        Grid.SetRowSpan(control, 3);
                        this.grid_root.Children.Add(control);
                        Panel.SetZIndex(control, int.MaxValue);
                    });
        }

        private void LoginControl_Loaded(object sender, RoutedEventArgs e)
        {
            double top = (this.ActualHeight - 400) / 3;
            this.gridLogin.Margin = new Thickness(0, top, 0, 0);

            BeWoApp.LoginControl = this;
        }

        private void ShowModalBackground()
        {
            this._ModalPopUpBackGround = new Grid();
            this._ModalPopUpBackGround.IsHitTestVisible = true;
            this._ModalPopUpBackGround.Background = Brushes.White;
            this._ModalPopUpBackGround.Opacity = .5;
            Grid.SetColumnSpan(this._ModalPopUpBackGround, 3);
            Grid.SetRowSpan(this._ModalPopUpBackGround, 3);
            this.grid_root.Children.Add(this._ModalPopUpBackGround);
            Panel.SetZIndex(this._ModalPopUpBackGround, int.MaxValue - 1);
        }

        private void button_login_Click(object sender, RoutedEventArgs e)
        {

			if (!String.IsNullOrEmpty(proxyname))
			{
				var webProxy = WebProxy.GetDefaultProxy();
				webProxy.UseDefaultCredentials = true;
				System.Net.WebRequest.DefaultWebProxy = new WebProxy(proxyname, true);

				if (String.IsNullOrEmpty(proxyUsername))
				{
					WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;
				}
				else
				{
					WebRequest.DefaultWebProxy.Credentials = new NetworkCredential(proxyUsername, proxypasswd);
				}
			}



			if (ProfileList.Count == 0 || profileSelectionComboBox.SelectedItem == null)
			{
				MessageBox.Show(
					"Es wurde kein gültiges Profil gefunden. Bitte erstellen Sie zunächst ein Profil. Klicken Sie dazu auf 'Erweitert' und anschließend auf den Button 'Profile bearbeiten'",
					"Ungültiges Profil", MessageBoxButton.OK, MessageBoxImage.Warning);
			}
			else
			{

				ChangeServerAndTenant(profileSelectionComboBox.SelectedItem as BeWoProfile);
				var lWaitLayer = new WaitLayer2();
				grid_root.Children.Add(lWaitLayer);

				string lUserName = TextBox_Username.Text;
				string lPassword = PasswordBox_Password.Password;
			    string lPIN = PINTextBox.Text;
				string lTenant = BeWoApp.Tenant;




				
				if (!String.IsNullOrEmpty(lPIN))
				{
					lPIN += "_" + System.Environment.MachineName;
				}
				Action<WaitLayer2, String, String, String, String> action = Login;
				action.BeginInvoke(lWaitLayer, lUserName, lPassword, lTenant, lPIN, cb => {}, null);
			}
        }
		
        private void Login(WaitLayer2 lWaitLayer, String lUserName, String lPassword, String lTenant, String lPIN)
        {
            try
            {
                //1. Versuch
                UserValidationResult result = TryLogin(lWaitLayer, lUserName, lPassword, lPIN );

                //2. Versuch
                if (result == UserValidationResult.UnkownError)
                {
                    ServiceFacade.DoOperationsServiceAsync(op => op.ResetTenant(lTenant),
                                    delegate
                                    {
                                        result = TryLogin(lWaitLayer ,lUserName, lPassword, lPIN);

                                        if (result == UserValidationResult.UnkownError)
                                        {
                                            //3. Versuch
                                            ServiceFacade.DoOperationsServiceAsync(op => op.ResetAllTenants(),
                                                    delegate
                                                    {
                                                        result = TryLogin(lWaitLayer,lUserName, lPassword, lPIN);

                                                        if (result == UserValidationResult.UnkownError)
                                                        {
                                                            this.Dispatch(delegate
                                                            {
                                                                grid_root.Children.Remove(lWaitLayer);
                                                                MessageBox.Show("Fehler beim Verbinden mit dem Server. Bitte überprüfen Sie Ihre Internetverbindung oder schreiben Sie eine E-Mail an den Support support@bewoplaner.de.", "Fehler bei der Anmeldung", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                                                            });
                                                        }
                                                    });
                                        }
                                    });
                }

                if (result == UserValidationResult.UserUnknown)
                {
                    this.Dispatch(delegate
                    {
                        grid_root.Children.Remove(lWaitLayer);
                        MessageBox.Show("Anmeldeinformationen nicht bekannt. Bitte überprüfen Sie den Benutzernamen und das Passwort!", "Fehler bei der Anmeldung", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    });
                }
                if (result == UserValidationResult.TenantUnknown)
                {
                    this.Dispatch(delegate
                    {
                        grid_root.Children.Remove(lWaitLayer);
                        MessageBox.Show("Die Kundennummer '" + lTenant + "' ist ungültig.", "Fehler bei der Anmeldung", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    });
                }
	            String pin = lPIN;
				
				if (!String.IsNullOrEmpty(lPIN) && lPIN.IndexOf('_') >= 0)
				{
					pin = lPIN.Substring(0, lPIN.IndexOf('_'));
				}

				if (result == UserValidationResult.IncorrectPin)
				{
					this.Dispatch(delegate
					{
						grid_root.Children.Remove(lWaitLayer);
						MessageBox.Show("Die Pin '" + pin + "' ist unbekannt!", "Fehler bei der Anmeldung", MessageBoxButton.OK, MessageBoxImage.Exclamation);
					});
				}
				if (result == UserValidationResult.PinAlreadyUsed)
				{
					this.Dispatch(delegate
					{
						grid_root.Children.Remove(lWaitLayer);
						MessageBox.Show("Die Pin '" + pin + "' wurde bereits verwendet!", "Fehler bei der Anmeldung", MessageBoxButton.OK, MessageBoxImage.Exclamation);
					});
				}
				if (result == UserValidationResult.PinExpired)
				{
					this.Dispatch(delegate
					{
						grid_root.Children.Remove(lWaitLayer);
						MessageBox.Show("Die Pin '" + pin + "' ist bereits abgelaufen!", "Fehler bei der Anmeldung", MessageBoxButton.OK, MessageBoxImage.Exclamation);
					});
				}
                if (result == UserValidationResult.PasswordExpired)
                {
                    //this.Dispatch(delegate
                    //{
                    //    grid_root.Children.Remove(lWaitLayer);
                    //    //MessageBox.Show("Das Passwort ist abgelaufen!", "Fehler bei der Anmeldung", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    //    //var pav = new PasswortAenderungsView();
                    //    //pav.ShowDialog();
                    //});
                }
                // Wegen fehlerhaftem Profil, sonst wird lWaitLayer nicht entfernt und eine Korrektur des Profils ist unmöglich ohne den BeWoPlaner neuzustarten.
                if (result == UserValidationResult.UnkownError)
                {
                    Thread.Sleep(2000);
                    this.Dispatch(delegate { grid_root.Children.Remove(lWaitLayer); });
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private UserValidationResult TryLogin(WaitLayer2 lWaitLayer, string lUserName, string lPassword, string lPIN = "")
        {
            UserValidationResult? result = null;
	        
            if (!string.IsNullOrEmpty(lUserName) && !string.IsNullOrEmpty(lPassword))
            {
				String tempUsername = lUserName;
				try
				{
					var version = Environment.OSVersion.VersionString;
					tempUsername = String.Format("{0}//Version={1}", lUserName, version);
				}
				catch (Exception)
				{
					// do nothing
				}

                try
                {
                    ServiceFacade.DoUserServiceAsync(s =>
                    {
                        try
                        {
							return s.IsUserValid(tempUsername, lPassword, lPIN);
                        }
                        catch (Exception)
                        {
                            return UserValidationResult.UnkownError;
                        }
                    },
                    r =>
                    {
                        result = r;
                        LoginResult(lWaitLayer,r, lUserName, lPassword, lPIN );
                    }, true);
                }
                catch (FaultException<BeWoFault>)
                {
                    result = UserValidationResult.UnkownError;
                }
            }
            else
            {
                if(result == null)
                    result = UserValidationResult.UserUnknown;
            }

            while (!result.HasValue)
            {
                Thread.Sleep(100);
            }

            return result.Value;
        }

        private void LoginResult( WaitLayer2 lWaitLayer, UserValidationResult result, String lUserName, String lPassword, String lPIN = "")
        {
            if (result == UserValidationResult.UserValid)
            {
				//this.Dispatch(delegate
				//{
				//    if (BeWoApp.Tenant == "demo")
				//    {
				//        var dlg = new ConfirmDemoDialog();
				//        dlg.Topmost = true;
				//        dlg.Show();
				//    }
				//});
				
                BeWoApp.UserName = lUserName;
                BeWoApp.UserPassword = lPassword;

                ServiceFacade.DoUserServiceAsync(s2 => s2.LoadUserByLoginName(lUserName),
                    r2 =>
                    {
                        BeWoApp.LoggedOnUser = r2;
						
                        ServiceFacade.DoOperationsServiceAsync(s => s.GetMandator(),
                            m =>
                            {
                                BeWoApp.Mandator = m;
                                this.Dispatch(delegate
                                {
                                    if (LoginSuccessful != null)
                                        LoginSuccessful(this, new EventArgs());
                                });
                            });
                    }, true);
            }
            else if (result == UserValidationResult.PasswordExpired)
            {
                BeWoApp.UserName = lUserName;
                BeWoApp.UserPassword = lPassword;

                ServiceFacade.DoUserServiceAsync(s2 => s2.LoadUserByLoginName(lUserName),
                    r2 =>
                    {
                        BeWoApp.LoggedOnUser = r2;

                        ServiceFacade.DoOperationsServiceAsync(s => s.GetMandator(),
                            m =>
                            {
                                BeWoApp.Mandator = m;
                                this.Dispatch(delegate
                                {
                                    grid_root.Children.Remove(lWaitLayer);
                                    MessageBox.Show("Das Passwort ist abgelaufen!", "Fehler bei der Anmeldung", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                                        
                                    var pav = new PasswortAenderungsView();
                                    pav.ShowDialog();

                                    if (pav.abr == 1)
                                    {

                                    }
                                    else {
                                        if (LoginSuccessful != null)
                                            LoginSuccessful(this, new EventArgs());
                                    }
                                });
                            });
                    }, true);
            }
        }

        private void Hyperlink_OnRequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo((sender as Hyperlink).NavigateUri.ToString()));
        }

        private void TextBox_Username_OnGotFocus(object sender, RoutedEventArgs e)
        {
            TextBox_Username.SelectAll();
        }

        private void PasswordBox_Password_OnGotFocus(object sender, RoutedEventArgs e)
        {
            PasswordBox_Password.SelectAll();
        }

        private void button_addProfile_Click(object sender, RoutedEventArgs rea)
        {
            var newProfileList = new List<BeWoProfile>();
            newProfileList.AddRange(ProfileList);

            try
            {
                Mouse.OverrideCursor = Cursors.Wait;

                var p = new ProfileEditView { Profiles = newProfileList };

                profileEditPopUp.Child = p;

                if (p.CommandBindings.Count != 0)
                    return;

                p.CommandBindings.Add(
                    new CommandBinding(
                        ApplicationCommands.Close,
                        (s, e) =>
                        {
                            profileEditPopUp.Child = null;
                        }));
                p.CommandBindings.Add(
                    new CommandBinding(
                        ApplicationCommands.Save,
                        (s, e) =>
                        {
                            ProfileList = p.Profiles;
                            SaveProfileListToFile();
                            profileEditPopUp.Child = null;

                            //BeWoProfile profile = profileSelectionComboBox.SelectedItem as BeWoProfile;
                            //ChangeServerAndTenant(profile);
                        }));
            }
            finally
            {
                Mouse.OverrideCursor = null;
            }

        }

		private void button_configureProxy_Click(object sender, RoutedEventArgs rea)
	    {
            ProxyLoginView proxyLogin = new ProxyLoginView();
			proxyLogin.WindowStartupLocation = WindowStartupLocation.CenterScreen;
			
			proxyLogin.ShowDialog();
			ReadProxyName();
	    }

        private void ReadProxyName()
        {
            int counter = 0;
            string line;
            string[] datai = new string[3];

            try
            {
				var filePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\proxy.dat";
				if (!File.Exists(filePath))
				{
					filePath = Path.Combine(BeWoApp.GetAndCreateUserAppDataPath(), "proxy.dat");
				}

                var file = new System.IO.StreamReader(filePath);
                while ((line = file.ReadLine()) != null)
                {
                    byte[] decbuff = Convert.FromBase64String(line);
                    var x = System.Text.Encoding.UTF8.GetString(decbuff);

                    datai[counter] = x;
                    counter++;
                }

                file.Close();
                
                proxyname = datai[0];
                proxyUsername = datai[1];
                proxypasswd = datai[2];

                proxyTextBox.Text = proxyname;

            }catch(IOException i){
                //Fehlermeldung
            }
            
        }


		

        private void SaveProfileListToFile()
        {
            var sw = new StreamWriter(new FileStream(_ProfilesFilePath, FileMode.Create), Encoding.UTF8);

			foreach (var profile in ProfileList)
			{
				if (profile.Tenant != "demo")
					sw.WriteLine("{0}|{1}|{2}", profile.Name, profile.Server, profile.Tenant);
			}
	        sw.Flush();
            sw.Close();

            profileSelectionComboBox.ItemsSource = ProfileList;
            profileSelectionComboBox.Items.Refresh();

            // Workaround, um profileSelectionComboBox.SelectedItem zu aktualisieren
            if (profileSelectionComboBox.ItemsSource == null)
                return;

            //ChangeServerAndTenant(profileSelectionComboBox.SelectedItem as BeWoProfile);
            //int itemssourcecount = ((List<BeWoProfile>) profileSelectionComboBox.ItemsSource).Count;
            //int si = profileSelectionComboBox.SelectedIndex;

            //profileSelectionComboBox.SelectedIndex = (si + 1) % itemssourcecount;
            //profileSelectionComboBox.SelectedIndex = itemssourcecount == 1 || si == -1 ? 0 : si;
        }

        private void ChangeServerAndTenant(BeWoProfile profile)
        {
            try
            {
                //button_login.IsEnabled = false;

                if (profile != null)
                {
                    if (String.IsNullOrEmpty(profile.Server))
                    {
                        MessageBox.Show(
                            String.Format("Das gewählte Profil '{0}' enthält einen ungültigen Servernamen.",
                                          profile.Name),
                            "Ungültiges Profil", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                    if (String.IsNullOrEmpty(profile.Tenant))
                    {
                        MessageBox.Show(
                            String.Format("Das gewählte Profil '{0}' enthält eine ungültige Kundennummer.", profile.Name),
                            "Ungültiges Profil", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }


                    
					//if (BeWoApp.Tenant == "7635986435")
					//{
					//	if (profile.Server != "3")
					//	{
					//		profile.Server = "3";
					//		SaveProfileListToFile();
					//	}

					//}

	                var server = GetServerFromTenant(profile.Tenant);
	                if (!String.IsNullOrEmpty(server) && server != profile.Server)
	                {
		                profile.Server = server;
						SaveProfileListToFile();
	                }

	                BeWoApp.Tenant = profile.Tenant;
					BeWoApp.ServerName = GetNumericServerName(profile.Server);
                    BeWoApp.ServerAddress = profile.Server;
                    //button_login.IsEnabled = true;
                }
            }

            catch (UriFormatException ex)
            {
                MessageBox.Show(
                    "Die angegebene Serveradresse ist nicht korrekt. Bitte bearbeiten Sie das verwendete Profil. Klicken Sie dazu auf 'Erweitert' und anschließend auf den Button 'Profile bearbeiten'",
                    "Ungültiges Profil", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }

        private void ShowProfileStackPanel(object sender, RoutedEventArgs e)
        {
            if (profileLabel.Visibility == Visibility.Visible)
            {
                profileLabel.Visibility = Visibility.Collapsed;
                profileStackPanel.Visibility = Visibility.Collapsed;
	            proxyLabel.Visibility = Visibility.Collapsed;
				proxyStackPanel.Visibility = Visibility.Collapsed;
            }
        }

        private double lineYCoordTo;
        private double lineYCoordFrom;
        private double heightFrom;
        private double heightTo;

        public double HeightFrom
        {
            get { return heightFrom; }
            set
            {
                heightFrom = value;
                OnPropertyChanged("HeightFrom");
            }
        }
        public double HeightTo
        {
            get { return heightTo; }
            set
            {
                heightTo = value;
                OnPropertyChanged("HeightTo");
            }
        }
        public double LineYCoordFrom
        {
            get { return lineYCoordFrom; }
            set
            {
                lineYCoordFrom = value;
                OnPropertyChanged("LineYCoordFrom");
            }
        }
        public double LineYCoordTo
        {
            get { return lineYCoordTo; }
            set
            {
                lineYCoordTo = value;
                OnPropertyChanged("LineYCoordTo");
            }
        }

        private void AnimationComplete(object sender, EventArgs e)
        {
            double tmp = HeightFrom;
            HeightFrom = HeightTo;
            HeightTo = tmp;
            if (HeightFrom > HeightTo)
            {
                showProfileSelectionBtn.Content = "Ausblenden";
                profileLabel.Visibility = Visibility.Visible;
                profileStackPanel.Visibility = Visibility.Visible;
				proxyLabel.Visibility = Visibility.Visible;
				proxyStackPanel.Visibility = Visibility.Visible;
            }
            else
            {
                showProfileSelectionBtn.Content = "Erweitert";
            }
        }

        private void Animation2Complete(object sender, EventArgs e)
        {
            double tmp2 = LineYCoordFrom;
            LineYCoordFrom = LineYCoordTo;
            LineYCoordTo = tmp2;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }

	    private bool pwvViewOffen;
	    private void PasswortVergessenLinkOnRequestNavigate(object sender, RequestNavigateEventArgs e)
	    {
		    if (pwvViewOffen) return;

		    var p = new PwVergessenView();
		    p.Closed += (s, ex) => { pwvViewOffen = false; };
			p.Show();

		    pwvViewOffen = true;
	    }
    }

    public class BeWoProfile
    {
        public string Name { get; set; }
        public string Server { get; set; }
        public string Tenant { get; set; }

        public BeWoProfile(string pname, string pserver, string ptenant)
        {
            Name = pname;
            Server = pserver;
            Tenant = ptenant;
			if (Name == null)
				Name = String.Empty;
        }

        public override string ToString()
        {
            return Name;
        }
    }
}
