using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Model;
using Sunny.UI;
using Sunny.UI.Win32;
using Permission;
using User = Model.User;
using PlcUiForm;
namespace YangjieTester.用户管理
{
    [FormDescriptionAttribute("登录")]
    public partial class SignInForm : PlcBaseForm
    {
        public SignInForm()
        {
            InitializeComponent();
        }
        string UserName,Password;
        public SignInForm(string userName,string password)
        {
            UserName = userName;
            Password = password;
            InitializeComponent();
        }
        private void FormSignIn_Load(object sender, EventArgs e)
        {
            txtUsername.Text = UserName;
            txtPassword.Text = Password;
        }

        bool GetInputUser(out User user)
        {
            string name = txtUsername.Text.Trim();
            string password = txtPassword.Text.Trim();

            if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(password))
            {
                user = new Model.User(name, password);
                return true;
            }
            user = null;
            return false;
        }
        
        private void btnSignIn_Click(object sender, EventArgs e)
        {
            if(GetInputUser(out User user))
            { 
                if (UserService.ValidateUser(user, out string err))
                {
                    PermissionManager.SignIn(user);
                    MessageBox.Show($"登录成功，权限：{Enum.GetName(typeof(PermissionLevel), user.PermissionLevel)}", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    DialogResult = DialogResult.OK;
                    Close();
                }
                else
                {
                    MessageBox.Show($"登录失败：{err}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }
        private void btnSignOut_Click(object sender, EventArgs e)
        {
            txtUsername.Text = null;
            txtPassword.Text = null;
            PermissionManager.SignOut();
        }

        private void btnSignUp_Click(object sender, EventArgs e)
        {
            new SignUpForm().ShowDialog();
        }
    }
}
