UserLoginControl.cs 7.08 KB
using System;
using System.Drawing;
using System.Windows.Forms;
using MoyaAdminLib;
using System.Web.Script.Serialization;
using System.Net;
using ThermoPrinterLibrary;

namespace MoyaSignup
{
    public partial class UserLoginControl : UserControl
    {
        public event EventHandler LoginOk;

        public delegate void ThermoPrinterEvent(ThermoPrinter.Models model);

        public event ThermoPrinterEvent SetPrinter;
        public User CurrentUser;

        public UserLoginControl()
        {
            InitializeComponent();
            SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            BackColor = Color.Transparent;
            infoLabel.Text = "Hei! Kirjoita sähköpostiosoitteesi";
        }

        private void UserLoginControl_Load(object sender, EventArgs e)
        {
        }

        private void TxtEmail_TextChanged(object sender, EventArgs e)
        {
            var txt = txtEmail.Text;
            if (IsValidEmail(txt))
            {
                var client = new RestClient();
                try
                {
                    var json = client.MakeRequest("user", "email=" + txtEmail.Text);
                    var ser = new JavaScriptSerializer();
                    var euser = ser.Deserialize<Eventuser>(json);
                    if (euser != null)
                    {
                        btnNewProfile.Visible = false;
                        CurrentUser = new User(euser);
                        infoLabel.Text = "Hei! " + CurrentUser + " Kirjoita salasanasi ja kirjaudu";
                        ShowLogin(true);
                    }
                }
                catch (WebException ex)
                {
                    var apiException = ex as MoyaApiException;
                    if (apiException != null && apiException.StatusCode == HttpStatusCode.NotFound)
                    {
                        CurrentUser = null;
                        infoLabel.Text = "Uusi kävijä?";
                        btnNewProfile.Visible = true;
                        ShowLogin(false);
                    }
                    else
                    {
                        ShowLogin(false);

                        Logger.Error("Connection to MoyaApi failed", ex);

                        MessageBox.Show(
                            "Yhteys taustajärjestelmään epäonnistui. Ota yhteys infoon.",
                            "Järjestelmävirhe",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error
                        );
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error("Unexpected exception", ex);

                    MessageBox.Show(
                        "Odottamaton virhe. Ota yhteys infoon.",
                        "Järjestelmävirhe",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error
                    );
                }
            }
            else
            {
                ShowLogin(false);
                if (txtEmail.Text == "thermo2")
                {
                    SetPrinter?.Invoke(ThermoPrinter.Models.IDP3210);
                    txtEmail.Text = "OK";
                }
                else if (txtEmail.Text == "thermo1")
                {
                    SetPrinter?.Invoke(ThermoPrinter.Models.TMT188II);
                    txtEmail.Text = "OK";
                }
                
                CurrentUser = null;
                btnNewProfile.Visible = false;
                infoLabel.Text = "Hei! Kirjoita sähköpostiosoitteesi";
            }
        }

        private static bool IsValidEmail(string email)
        {
            if (!email.Contains("@") || !email.Contains("."))
                return false;

            var parts = email.Split(new[] {"@"}, StringSplitOptions.RemoveEmptyEntries);
            if (parts.Length == 2)
            {
                if (!parts[1].Contains("."))
                    return false;
                var domainparts = parts[1].Split(new[] {"."}, StringSplitOptions.RemoveEmptyEntries);
                if (domainparts.Length < 2)
                    return false;
                var ltd = domainparts[domainparts.Length - 1];
                if (ltd.Length < 2)
                    return false;
            }
            else
            {
                return false;
            }

            try
            {
                var addr = new System.Net.Mail.MailAddress(email);
                return addr.Address == email;
            }
            catch
            {
                return false;
            }
        }

        private void ShowLogin(bool show)
        {
            if (show)
            {
                passwordTextBox.Visible = true;
                loginButton.Visible = true;
            }
            else
            {
                passwordTextBox.Visible = false;
                loginButton.Visible = false;
                passwordTextBox.Clear();
            }
        }

        private void DoLogin()
        {
            var client = new RestClient(RestClient.ApiURL, HttpVerb.POST)
            {
                PostData = "password=" + passwordTextBox.Text,
                ContentType = "application/x-www-form-urlencoded"
            };

            try
            {
                var json = client.MakeRequest("v2/user/" + CurrentUser.UserId + "/check-password");

                // MoyaWeb/rest/user/eventusers
                var ser = new JavaScriptSerializer();
                var euser = ser.Deserialize<Eventuser>(json);
                if (euser != null)
                {
                    CurrentUser = new User(euser)
                    {
                        Email = txtEmail.Text
                    };

                    LoginOk?.Invoke(this, null);
                }
                else
                {
                    WrongPass();
                }
            }
            catch (Exception)
            {
                WrongPass();
            }
        }

        private void LoginButton_Click(object sender, EventArgs e)
        {
            DoLogin();
        }

        private void WrongPass()
        {
            infoLabel.Text = "Väärä salasana. Syötä salasana uudelleen";
        }

        private void PasswordTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                DoLogin();
        }

        private void BtnNewProfile_Click(object sender, EventArgs e)
        {
            CurrentUser = new User
            {
                Email = txtEmail.Text
            };

            //Send info to parent control
            LoginOk?.Invoke(this, null);
        }


        internal void Clear()
        {
            CurrentUser = null;
            txtEmail.Text = "";
            passwordTextBox.Visible = false;
            passwordTextBox.Text = "";
            SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            BackColor = Color.Transparent;
            infoLabel.Text = "Hei! Kirjoita sähköpostiosoitteesi";
            loginButton.Visible = false;
        }
    }
}