namespace AutorentWinForms;

public sealed class LoginForm : Form
{
    private readonly Database _db;
    private readonly TextBox _loginBox = new() { Text = "garanin_gi", Width = 220 };
    private readonly TextBox _passwordBox = new() { UseSystemPasswordChar = true, Width = 220 };
    private readonly Label _message = new() { AutoSize = true, ForeColor = Color.Firebrick };

    public UserSession? Session { get; private set; }

    public LoginForm(Database db)
    {
        _db = db;
        Text = "Автопрокат - вход";
        StartPosition = FormStartPosition.CenterScreen;
        FormBorderStyle = FormBorderStyle.FixedDialog;
        MaximizeBox = false;
        MinimizeBox = false;
        ClientSize = new Size(420, 230);
        Font = new Font("Segoe UI", 10F);

        var title = new Label
        {
            Text = "Информационная система «Автопрокат»",
            Font = new Font(Font, FontStyle.Bold),
            AutoSize = true,
            Location = new Point(32, 26)
        };

        var hint = new Label
        {
            Text = "Вход выполняется по учетной записи PostgreSQL.",
            ForeColor = Color.DimGray,
            AutoSize = false,
            Size = new Size(350, 24),
            Location = new Point(32, 58)
        };

        var loginLabel = new Label { Text = "Логин", AutoSize = true, Location = new Point(32, 104) };
        _loginBox.Location = new Point(150, 100);
        var passwordLabel = new Label { Text = "Пароль", AutoSize = true, Location = new Point(32, 144) };
        _passwordBox.Location = new Point(150, 140);

        var loginButton = new Button { Text = "Войти", Width = 105, Height = 34, Location = new Point(265, 178) };
        loginButton.Click += (_, _) => TryLogin();
        AcceptButton = loginButton;

        _message.Location = new Point(32, 186);

        Controls.AddRange([title, hint, loginLabel, _loginBox, passwordLabel, _passwordBox, _message, loginButton]);
    }

    private void TryLogin()
    {
        Session = _db.Authenticate(_loginBox.Text, _passwordBox.Text);
        if (Session is null)
        {
            _message.Text = "Неверный логин или пароль.";
            return;
        }

        _db.SetSession(Session);
        DialogResult = DialogResult.OK;
        Close();
    }
}
