using System;
using System.IO;
using System.Windows.Forms;

namespace MyShop
{
    public partial class LoginForm : Form
    {
        public bool succeeded;
        public string CurrentUserName;

        public LoginForm()
        {
            InitializeComponent();
            LoadSavedUserName();
        }

        private void LoadSavedUserName()
        {
            txtUserName.Text = Properties.Settings.Default.SavedUserName;
            chkRememberUserName.Checked = txtUserName.Text.Length > 0;
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            usersTableAdapter.FillByUserNameAndPass(myShopDataSet.Users, txtUserName.Text, txtPassword.Text);

            if (myShopDataSet.Users.Rows.Count > 0)
            {
                SaveUserName();
                CurrentUserName = txtUserName.Text;
                succeeded = true;

                MainForm mainForm = new MainForm(CurrentUserName);
                mainForm.FormClosed += new FormClosedEventHandler(MainForm_FormClosed);
                mainForm.Show();
                this.Hide();
            }
            else
            {
                WriteFailedLoginLog(txtUserName.Text);
                MessageBox.Show("خطا: نام کاربری یا گذرواژه صحیح نیست.", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            succeeded = false;
            this.Close();
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.Close();
        }

        private void WriteFailedLoginLog(string userName)
        {
            string logPath;
            string logText;

            logPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log.txt");
            logText = "ورود ناموفق: " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") +
                " - نام کاربری وارد شده: " + userName + Environment.NewLine;

            try
            {
                File.AppendAllText(logPath, logText, System.Text.Encoding.UTF8);
            }
            catch
            {
                MessageBox.Show("خطا در ثبت ورود ناموفق در پرونده Log.txt", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void SaveUserName()
        {
            if (chkRememberUserName.Checked)
            {
                Properties.Settings.Default.SavedUserName = txtUserName.Text;
            }
            else
            {
                Properties.Settings.Default.SavedUserName = "";
            }

            Properties.Settings.Default.Save();
        }

        private void usersBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {

        }
    }
}
