using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace hukpiWinApp.Forms.Admin
{
    public partial class EditUserForm : BaseForm
    {
        decimal userId;
        decimal groupId;

        public EditUserForm(decimal userId)
        {
            InitializeComponent();

            this.userId = userId;
            fillComboUserGroups(true);
            loadDataToForm();
        }

        private void fillComboUserGroups(bool justActives)
        {
            comboBoxUserGroup.DataSource = Utils.getUserGroupsForCombo(Properties.Settings.Default.ComboBoxNotSelected,justActives);
            comboBoxUserGroup.DisplayMember = "Description";
            comboBoxUserGroup.ValueMember = "Id";
        }

        private void loadDataToForm()
        {
            hukpiDatabaseDataSetTableAdapters.UsersTableAdapter usersAdapter = new hukpiWinApp.hukpiDatabaseDataSetTableAdapters.UsersTableAdapter();
            hukpiDatabaseDataSet.UsersDataTable usersData = usersAdapter.GetDataByUserId(this.userId);

            this.groupId = Utils.getDecimalValueFromDB(usersData[0]["groupId"]);

            textBoxUserName.Text = usersData[0]["UserName"].ToString();
            textBoxFullName.Text = usersData[0]["UserFullName"].ToString();
            comboBoxUserGroup.SelectedValue = Utils.getIntValueFromDB(usersData[0]["groupId"]);
            checkBoxIsActive.Checked = Utils.isCheckedFromDBDecimal(Convert.ToDecimal(usersData[0]["isActive"]));

            usersData.Dispose();
            usersAdapter.Dispose();
        }

        private void textBoxFullName_Validating(object sender, CancelEventArgs e)
        {
            Utils.validateMustNonEmpty(errorProviderAddEditUser, textBoxFullName);
        }

        private void comboBoxUserGroup_Validating(object sender, CancelEventArgs e)
        {
            Utils.validateMustNonEmpty(errorProviderAddEditUser, comboBoxUserGroup);
        }

        private bool validatePasswordRe()
        {
            if (!"".Equals(textBoxPassword.Text.Trim()))
            {
                if (Utils.validateMustNonEmpty(errorProviderAddEditUser, textBoxPasswordRe))
                {
                    if (!textBoxPasswordRe.Text.Equals(textBoxPassword.Text))
                    {
                        errorProviderAddEditUser.SetError(textBoxPasswordRe, "A jelszó és a jelszó megerősítése nem egyezik!");
                        return false;
                    }
                    else
                    {
                        errorProviderAddEditUser.SetError(textBoxPasswordRe, "");
                        return true;
                    }
                }
                return false;
            }
            return true;
        }

        private void textBoxPasswordRe_Validating(object sender, CancelEventArgs e)
        {
            validatePasswordRe();
        }

        private bool validateForm()
        {
            bool isValidFullName = Utils.validateMustNonEmpty(errorProviderAddEditUser, textBoxFullName);
            bool isValidPasswordRe = validatePasswordRe();
            bool isValidUserGroup = Utils.validateMustNonEmpty(errorProviderAddEditUser, comboBoxUserGroup);

            return isValidFullName && isValidPasswordRe && isValidUserGroup;
        }

        private bool saveModifiedUser()
        {
            if (!validateForm())
            {
                MessageBox.Show(ErrorMessages.Default.invalidFormInputData);
                return false;
            }
            else
            {
                using (hukpiLINQDataContext linqContext = new hukpiLINQDataContext())
                {
                    using (var transaction = new System.Transactions.TransactionScope())
                    {
                        User userData = linqContext.Users.Single(p => p.usersId == this.userId);

                        userData.userFullName = textBoxFullName.Text;
                        userData.groupId = Convert.ToDecimal(comboBoxUserGroup.SelectedValue);
                        userData.isActive = checkBoxIsActive.Checked ? 1 : 0;

                        if (!"".Equals(textBoxPassword.Text))
                        {
                            userData.userPassword = Utils.getMD5Hash(textBoxPassword.Text);
                        }

                        linqContext.SubmitChanges();
                        transaction.Complete();
                    }
                }

                MessageBox.Show("Sikeres mentés!");
                return true;
            }
        }

        private void saveLayoutUser_SaveButtonClick()
        {
            if (saveModifiedUser())
            {
                ((MainForm)this.MdiParent).refreshDataInAllChildForm();
                this.Dispose();
            }
        }

        private void saveLayoutUser_CancelButtonClick()
        {
            this.Dispose();
        }
    }
}
