using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace hukpiWinApp
{
    static class Utils
    {
        public static bool isCheckedFromDBDecimal(decimal DBValue)
        {
            if (DBValue == 1)
            {
                return true;
            }
            else if (DBValue == 0)
            {
                return false;
            }
            else
            {
                throw new Exception("Az adatbázisban tárolt logikai értékrendszer nem egyezik meg a program által használttal!");
            }

        }
        
        public static bool isCheckedFromDB(string DBValue)
        {
            if (Properties.Settings.Default.DBYesChar.Equals(DBValue))
            {
                return true;
            }
            else if (Properties.Settings.Default.DBNoChar.Equals(DBValue) || "".Equals(DBValue))
            {
                return false;
            }
            else
            {
                throw new Exception("Az adatbázisban tárolt logikai értékrendszer nem egyezik meg a program által használttal!");
            }
            
        }

        public static char getDBValueForCheckBox(bool ischecked)
        {
            if (ischecked)
            {
                return Convert.ToChar(Properties.Settings.Default.DBYesChar);
            }
            else 
            {
                return Convert.ToChar(Properties.Settings.Default.DBNoChar);
            }
        }

        public static int getIntValueFromDB(object value)
        {
            if (Convert.IsDBNull(value))
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(value);
            }
        }

        public static decimal getDecimalValueFromDB(object value)
        {
            if (Convert.IsDBNull(value))
            {
                return 0;
            }
            else
            {
                return Convert.ToDecimal(value);
            }
        }

        public static bool isCancelAddEditFormClose(Form AddEditForm)
        {
            DialogResult res = MessageBox.Show("Biztosan be akarja zárni az ablakot?" +Environment.NewLine + "Minden nem mentett módosítás el fog veszni!", "Bezárás", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);

            if (res.Equals(DialogResult.Yes))
            {
                AddEditForm.Dispose();
                return false;
            }

            return true;
        }

        public static string implodeExtra(string stringBefore, List<string> list, string stringAfter, string glueString)
        {
            string result = "";

            for (int i = 0; i < list.Count - 1; i++)
            {
                result += stringBefore;
                result += list.ElementAt(i).ToString();
                result += stringAfter;
                result += glueString;
            }

            result += stringBefore;
            result += list.ElementAt(list.Count - 1).ToString();
            result += stringAfter;

            return result;
        }

        public static string implode(string glueString, List<decimal> list)
        {
            string result = "";

            for (int i = 0; i < list.Count-1;i++)
            {
                result += list.ElementAt(i).ToString();
                result += glueString;
            }

            result += list.ElementAt(list.Count - 1).ToString();

            return result;
        }

        public static string implode(string glueString, List<string> list)
        {
            string result = "";

            for (int i = 0; i < list.Count - 1; i++)
            {
                result += list.ElementAt(i).ToString();
                result += glueString;
            }

            result += list.ElementAt(list.Count - 1).ToString();

            return result;
        }



        public static List<decimal> getTransportDaysIdBasedOnDays(List<string> days, bool inWinter)
        {
            List<decimal> transportDaysIdList = new List<decimal>();
            
            hukpiDatabaseDataSetTableAdapters.DefaultTransportDaysTableAdapter defTransportDays = new hukpiWinApp.hukpiDatabaseDataSetTableAdapters.DefaultTransportDaysTableAdapter();

            foreach(hukpiDatabaseDataSet.DefaultTransportDaysRow row in defTransportDays.GetByDaysList(days,inWinter))
            {
                transportDaysIdList.Add(Convert.ToDecimal(row["Dtdid"]));
            }

            if (transportDaysIdList.Count == 0)
            {
                return null;
            }
            else
            {
                return transportDaysIdList;
            }
        }

        public static List<decimal> getChoosenIdsFromListView(ListView listView)
        {
            if (listView.Items.Count == 0)
            {
                return null;
            }
            
            List<decimal> choosenIdsList = new List<decimal>();
            
            foreach (ListViewItem item in listView.Items)
            {
                if(item.SubItems.Count == 0)
                {
                    continue;
                }
                if (item.SubItems[1].Tag != null)
                {
                    choosenIdsList.Add(Convert.ToDecimal(item.SubItems[1].Tag));
                }
            }

            if (choosenIdsList.Count == 0)
            {
                return null;
            }
            else
            {
                return choosenIdsList;
            }
        }

        public static string getMD5Hash(string value)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] bs = System.Text.Encoding.UTF8.GetBytes(value);
            bs = x.ComputeHash(bs);
            System.Text.StringBuilder s = new System.Text.StringBuilder();
            foreach (byte b in bs)
            {
                s.Append(b.ToString("x2").ToLower());
            }
            return s.ToString();
        }

        #region Report eszközök
        public static List<string> getRouteCodesByIdList(List<decimal> routeCodesIdList)
        {
            List<string> routeCodesStrings = new List<string>();

            using (hukpiLINQDataContext linqContext = new hukpiLINQDataContext())
            {
                using (var transaction = new System.Transactions.TransactionScope())
                {
                    var routeCodes = from p in linqContext.RouteCodes
                                     where routeCodesIdList.ToArray<decimal>().Contains(p.RouteCodesId)
                                     select p;

                    foreach (RouteCode actRow in routeCodes)
                    {
                        routeCodesStrings.Add(actRow.Code.ToString());
                    }
                }
            }

            return routeCodesStrings;
        }

        public static List<string> getModalityCodesByIdList(List<decimal> modalityCodesIdList)
        {
            List<string> modalityCodesStrings = new List<string>();

            using (hukpiLINQDataContext linqContext = new hukpiLINQDataContext())
            {
                using (var transaction = new System.Transactions.TransactionScope())
                {
                    var modalityCodes = from p in linqContext.Modalities
                                        where modalityCodesIdList.ToArray<decimal>().Contains(p.ModalityId)
                                        select p;

                    foreach (Modality actRow in modalityCodes)
                    {
                        modalityCodesStrings.Add(actRow.ShortModality);
                    }
                }
            }

            return modalityCodesStrings;
        }
        #endregion

        #region Validációs eszközök

        public static bool IsAlphaNumeric(String strToCheck)
        {
            Regex objAlphaNumericPattern = new Regex("[^a-zA-Z0-9]");
            return !objAlphaNumericPattern.IsMatch(strToCheck);
        }
        
        public static bool IsValidUserName(String strToCheck)
        {
            Regex objAlphaNumericPattern = new Regex("[^a-zA-Z0-9.]");
            return !objAlphaNumericPattern.IsMatch(strToCheck);
        }

        public static bool validateUserName(ErrorProvider errorProvider, TextBox textBox)
        {
            textBox.Text = textBox.Text.Trim();
            
            if ("".Equals(textBox.Text))
            {
                errorProvider.SetError(textBox, "Kérem töltse ki a mezőt!");
                return false;
            }
            else
            {
                
                if (!IsValidUserName(textBox.Text))
                {
                    errorProvider.SetError(textBox, "A felhasználói név érvénytelen karaktert tartalmaz!\n(Érvényes karakterek: betűk és számok, valamint a pont(.))");
                    return false;
                }
                
                hukpiDatabaseDataSetTableAdapters.UsersTableAdapter usersAdapter = new hukpiWinApp.hukpiDatabaseDataSetTableAdapters.UsersTableAdapter();
                hukpiDatabaseDataSet.UsersDataTable usersData = usersAdapter.GetDataByUserName(textBox.Text);

                if (usersData.Count > 0)
                {
                    errorProvider.SetError(textBox, "Már van ilyen felhasználó!");
                    return false;
                }

                errorProvider.SetError(textBox, "");
                return true;
            }
        }

        public static bool validateMustBetweenNumbers(ErrorProvider errorProvider, TextBox textBox, double min, double max, bool mustNonEmpty)
        {
            double number;

            if (mustNonEmpty && "".Equals(textBox.Text.Trim()))
            {
                errorProvider.SetError(textBox, "Kérem töltse ki a mezőt!");
                return false;
            }
            else
            {
                if (!double.TryParse(textBox.Text, out number))
                {
                    errorProvider.SetError(textBox, "Kérem, csak számot adjon meg!");
                    return false;
                }
                else
                {
                    if (number >= min && number <= max)
                    {
                        errorProvider.SetError(textBox, "Az értéknek " + min + " és " + max + " közé kell esnie!");
                        return false;
                    }
                    else
                    {
                        errorProvider.SetError(textBox, "");
                        return true;
                    }
                }
            }
        }

        public static bool validateMustHaveDigitsOnly(ErrorProvider errorProvider, TextBox textBox, bool mustNonEmpty, ErrorIconAlignment iconAlign)
        {
            errorProvider.SetIconAlignment(textBox, iconAlign);
            
            if (!mustNonEmpty && "".Equals(textBox.Text.Trim()))
            {
                errorProvider.SetError(textBox, "");
                return true;
            }
            else if (mustNonEmpty && "".Equals(textBox.Text.Trim()))
            {
                errorProvider.SetError(textBox, "Kérem töltse ki a mezőt!");
                return false;
            }
            else
            {
                int number;

                bool hasDigitsOnly = int.TryParse(textBox.Text, out number);

                if (!hasDigitsOnly)
                {
                    errorProvider.SetError(textBox, "Kérem, csak számot adjon meg!");
                    return false;
                }
                else
                {
                    errorProvider.SetError(textBox, "");
                    return true;
                }
            }
        }

        public static bool validateMustHaveDigitsOnly(ErrorProvider errorProvider, TextBox textBox, bool mustNonEmpty)
        {
            if (!mustNonEmpty && "".Equals(textBox.Text.Trim()))
            {
                errorProvider.SetError(textBox, "");
                return true;
            }
            else if (mustNonEmpty && "".Equals(textBox.Text.Trim()))
            {
                errorProvider.SetError(textBox, "Kérem töltse ki a mezőt!");
                return false;
            }
            else
            {
                int number;

                bool hasDigitsOnly = int.TryParse(textBox.Text, out number);

                if (!hasDigitsOnly)
                {
                    errorProvider.SetError(textBox, "Kérem, csak számot adjon meg!");
                    return false;
                }
                else
                {
                    errorProvider.SetError(textBox, "");
                    return true;
                }
            }
        }

        public static bool validateMustNonEmpty(ErrorProvider errorProvider, TextBox textBox, ErrorIconAlignment iconAlign)
        {
            errorProvider.SetIconAlignment(textBox, iconAlign);
                
            if ("".Equals(textBox.Text.Trim()))
            {
                errorProvider.SetError(textBox, "Kérem töltse ki a mezőt!");
                return false;
            }
            else
            {
                errorProvider.SetError(textBox, "");
                return true;
            }
        }

        public static bool validateMustNonEmpty(ErrorProvider errorProvider, TextBox textBox)
        {
            if ("".Equals(textBox.Text.Trim()))
            {
                errorProvider.SetError(textBox, "Kérem töltse ki a mezőt!");
                return false;
            }
            else
            {
                errorProvider.SetError(textBox, "");
                return true;
            }
        }

        public static bool validateMustNonEmpty(ErrorProvider errorProvider, ComboBox comboBox)
        {
            if ((int)comboBox.SelectedValue == 0)
            {
                errorProvider.SetError(comboBox, "Válasszon a legördülő menüből!");
                return false;
            }
            else
            {
                errorProvider.SetError(comboBox, "");
                return true;
            }
        }

        #endregion


        #region Jogosultság kezelés
        public static void setRolesToButtons(Control container, Form mainInstance)
        {
            List<string> grantedModules = ((MainForm)mainInstance).getGrantedModules();

            foreach (Control c in container.Controls)
            {
                if (c.Tag == null || "".Equals(c.Tag.ToString().Trim()) || !grantedModules.Contains(c.Tag.ToString().Trim()))
                {
                    c.Visible = false;
                }
                //else
                //{
                //    c.Visible = true;
                //}

            }
        }

        public static void setRolesToButtonsElseVisibleTrue(Control container, Form mainInstance)
        {
            List<string> grantedModules = ((MainForm)mainInstance).getGrantedModules();

            foreach (Control c in container.Controls)
            {
                if (c.Tag == null || "".Equals(c.Tag.ToString().Trim()) || !grantedModules.Contains(c.Tag.ToString().Trim()))
                {
                    c.Visible = false;
                }
                else
                {
                    c.Visible = true;
                }

            }
        }
        #endregion


        public static string getGroupName(decimal groupId)
        {
            hukpiDatabaseDataSetTableAdapters.GroupsTableAdapter groupsDataAdapter = new hukpiWinApp.hukpiDatabaseDataSetTableAdapters.GroupsTableAdapter();
            hukpiDatabaseDataSet.GroupsDataTable groupsData = groupsDataAdapter.GetDataByGroupId(groupId);

            return groupsData[0]["GroupName"].ToString();
        }

        #region ListView feltöltők

        public static List<ListViewItem> getGrantedModulesForListView(decimal groupId)
        {
            List<ListViewItem> models = new List<ListViewItem>();

            hukpiDatabaseDataSetTableAdapters.GroupsAndGrantedModulesTableAdapter grantedModulesDataAdapter = new hukpiWinApp.hukpiDatabaseDataSetTableAdapters.GroupsAndGrantedModulesTableAdapter();
            hukpiDatabaseDataSet.GroupsAndGrantedModulesDataTable grantedModulesData = grantedModulesDataAdapter.GetDataByGroupId(groupId);

            ListViewItem item;
            ListViewItem.ListViewSubItem subItem;

            foreach (hukpiDatabaseDataSet.GroupsAndGrantedModulesRow row in grantedModulesData)
            {
                item = new ListViewItem(row["ModuleName"].ToString());
                item.Tag = row["grantedModulesId"].ToString();
                subItem = new ListViewItem.ListViewSubItem(item, row["ModuleDetails"].ToString());
                subItem.Tag = row["ProgramModulesId"].ToString();
                item.SubItems.Add(subItem);

                models.Add(item);
            }

            return models;
        }


        public static List<ListViewItem> getModulesForListView()
        {
            List<ListViewItem> models = new List<ListViewItem>();

            hukpiDatabaseDataSetTableAdapters.ProgramModulesTableAdapter programModulesDataAdapter = new hukpiWinApp.hukpiDatabaseDataSetTableAdapters.ProgramModulesTableAdapter();
            hukpiDatabaseDataSet.ProgramModulesDataTable programModulesData = programModulesDataAdapter.GetData();

            ListViewItem item;
            ListViewItem.ListViewSubItem subItem;

            foreach (hukpiDatabaseDataSet.ProgramModulesRow row in programModulesData)
            {
                item = new ListViewItem(row["ModuleName"].ToString());
                subItem = new ListViewItem.ListViewSubItem(item, row["ModuleDetails"].ToString());
                subItem.Tag = row["ProgramModulesId"].ToString();
                item.SubItems.Add(subItem);

                models.Add(item);
            }

            return models;
        }

        public static List<ListViewItem> getModalitiesForListView()
        {
            List<ListViewItem> models = new List<ListViewItem>();

            hukpiDatabaseDataSetTableAdapters.ModalityTableAdapter modalitiesDataAdapter = new hukpiWinApp.hukpiDatabaseDataSetTableAdapters.ModalityTableAdapter();
            hukpiDatabaseDataSet.ModalityDataTable modalitiesData = modalitiesDataAdapter.GetData();
            
            ListViewItem item;
            ListViewItem.ListViewSubItem subItem;

            foreach (hukpiDatabaseDataSet.ModalityRow row in modalitiesData)
            {
                item = new ListViewItem(row["ShortModality"].ToString());
                subItem = new ListViewItem.ListViewSubItem(item, row["Modality"].ToString());
                subItem.Tag = row["ModalityId"].ToString();
                item.SubItems.Add(subItem);

                models.Add(item);
            }

            return models;
        }

        public static List<ListViewItem> getRoutesForListView()
        {
            List<ListViewItem> models = new List<ListViewItem>();

            hukpiDatabaseDataSetTableAdapters.RouteCodesTableAdapter routeCodesDataAdapter = new hukpiWinApp.hukpiDatabaseDataSetTableAdapters.RouteCodesTableAdapter();
            hukpiDatabaseDataSet.RouteCodesDataTable routeCodesData = routeCodesDataAdapter.GetData();

            ListViewItem item;
            ListViewItem.ListViewSubItem subItem;

            foreach (hukpiDatabaseDataSet.RouteCodesRow row in routeCodesData)
            {
                item = new ListViewItem(row["Code"].ToString());
                subItem = new ListViewItem.ListViewSubItem(item, row["Details"].ToString());
                subItem.Tag = row["RouteCodesId"].ToString();
                item.SubItems.Add(subItem);
                
                models.Add(item);
            }

            return models;
        }

        #endregion

        #region ComboBox feltöltők

        public static List<IModel> getUserGroupsForCombo(string nonSelectedString, bool justActives)
        {
            List<IModel> models = new List<IModel>();

            hukpiDatabaseDataSetTableAdapters.GroupsTableAdapter groupsDataAdapter = new hukpiWinApp.hukpiDatabaseDataSetTableAdapters.GroupsTableAdapter();
            hukpiDatabaseDataSet.GroupsDataTable groupsData;

            if (justActives)
            {
                groupsData = groupsDataAdapter.GetDataByActives();
            }
            else
            {
                groupsData = groupsDataAdapter.GetData();
            }

            models.Add(new Model(0, nonSelectedString));

            string name;
            foreach (hukpiDatabaseDataSet.GroupsRow row in groupsData)
            {
                name = row["GroupName"].ToString();
                models.Add(new Model(getIntValueFromDB(row["GroupId"]), name));
            }

            return models;
        }

        public static List<IModel> getRegionsForCombo()
        {
            List <IModel> models = new List<IModel>();
            
            hukpiDatabaseDataSetTableAdapters.RegionsTableAdapter RegionsDataAdapter = new hukpiWinApp.hukpiDatabaseDataSetTableAdapters.RegionsTableAdapter();
            hukpiDatabaseDataSet.RegionsDataTable regionsData = RegionsDataAdapter.GetData();

            models.Add(new Model(0, Properties.Settings.Default.ComboBoxNotSelected));

            string name;
            foreach (hukpiDatabaseDataSet.RegionsRow row in regionsData)
            {
                name = row["RegionCode"].ToString() + " - " + row["RegionName"].ToString();
                models.Add(new Model(getIntValueFromDB(row["RegionsId"]), name));
            }

            return models;
        }

        public static List<IModel> getContractTypesForCombo()
        {
            List<IModel> models = new List<IModel>();

            hukpiDatabaseDataSetTableAdapters.ContractTypesTableAdapter ContractDataAdapter = new hukpiWinApp.hukpiDatabaseDataSetTableAdapters.ContractTypesTableAdapter();
            hukpiDatabaseDataSet.ContractTypesDataTable contractData = ContractDataAdapter.GetData();

            models.Add(new Model(0, Properties.Settings.Default.ComboBoxNotSelected));
            foreach (hukpiDatabaseDataSet.ContractTypesRow row in contractData)
            {
                models.Add(new Model(getIntValueFromDB(row["ContractTypesId"]), Convert.ToString(row["ContractTypeName"])));
            }

            return models;
        }

        public static List<IModel> getCompanyDepotsForCombo()
        {
            List<IModel> models = new List<IModel>();

            hukpiDatabaseDataSetTableAdapters.CompanyDepotsTableAdapter companyDepotsDataAdapter = new hukpiWinApp.hukpiDatabaseDataSetTableAdapters.CompanyDepotsTableAdapter();
            hukpiDatabaseDataSet.CompanyDepotsDataTable companyDepotsData = companyDepotsDataAdapter.GetData();

            models.Add(new Model(0, Properties.Settings.Default.ComboBoxNotSelected));

            string name;

            foreach (hukpiDatabaseDataSet.CompanyDepotsRow row in companyDepotsData)
            {
                name = row["Name"].ToString() + " ( " + row["Place"].ToString() + " )";
                models.Add(new Model(getIntValueFromDB(row["CompanyDepotsId"]), name));
            }

            return models;
        }

        public static List<IModel> getModalitiesForCombo()
        {
            List<IModel> models = new List<IModel>();

            hukpiDatabaseDataSetTableAdapters.ModalityTableAdapter modalitiesDataAdapter = new hukpiWinApp.hukpiDatabaseDataSetTableAdapters.ModalityTableAdapter();
            hukpiDatabaseDataSet.ModalityDataTable modalitiesData = modalitiesDataAdapter.GetData();

            models.Add(new Model(0, Properties.Settings.Default.ComboBoxNotSelected));

            string name;

            foreach (hukpiDatabaseDataSet.ModalityRow row in modalitiesData)
            {
                name = row["ShortModality"].ToString() + " - " + row["Modality"].ToString();
                models.Add(new Model(getIntValueFromDB(row["ModalityId"]), name));
            }

            return models;
        }

        public static List<IModel> getRoutesForCombo()
        {
            List<IModel> models = new List<IModel>();

            hukpiDatabaseDataSetTableAdapters.RouteCodesTableAdapter routeCodesDataAdapter = new hukpiWinApp.hukpiDatabaseDataSetTableAdapters.RouteCodesTableAdapter();
            hukpiDatabaseDataSet.RouteCodesDataTable routeCodesData = routeCodesDataAdapter.GetData();

            models.Add(new Model(0, Properties.Settings.Default.ComboBoxNotSelected));

            string name;

            foreach (hukpiDatabaseDataSet.RouteCodesRow row in routeCodesData)
            {
                name = row["Code"].ToString() + " - " + row["Details"].ToString();
                models.Add(new Model(getIntValueFromDB(row["RouteCodesId"]), name));
            }

            return models;
        }

        public static List<IModel> getContainersForCombo()
        {
            List<IModel> models = new List<IModel>();

            hukpiDatabaseDataSetTableAdapters.ContainersTableAdapter containersDataAdapter = new hukpiWinApp.hukpiDatabaseDataSetTableAdapters.ContainersTableAdapter();
            hukpiDatabaseDataSet.ContainersDataTable containersData = containersDataAdapter.GetData();

            models.Add(new Model(0, Properties.Settings.Default.ComboBoxNotSelected));

            string name;

            foreach (hukpiDatabaseDataSet.ContainersRow row in containersData)
            {
                name = row["ContainerName"].ToString();
                models.Add(new Model(getIntValueFromDB(row["ContainersId"]), name));
            }

            return models;
        }

        public static List<IModel> getClassesForCombo(string classNumber)
        {
            List<IModel> models = new List<IModel>();

            hukpiDatabaseDataSetTableAdapters.ClassesTableAdapter classesDataAdapter = new hukpiWinApp.hukpiDatabaseDataSetTableAdapters.ClassesTableAdapter();
            hukpiDatabaseDataSet.ClassesDataTable classesData = classesDataAdapter.GetDataByClassNumber(classNumber);

            models.Add(new Model(0, Properties.Settings.Default.ComboBoxNotSelected));

            string name;

            foreach (hukpiDatabaseDataSet.ClassesRow row in classesData)
            {
                name = row["ItemNumber"].ToString() + " - " + row["ItemName"].ToString();
                models.Add(new Model(getIntValueFromDB(row["ClassesId"]), name));
            }

            return models;
        }

        public static List<IModel> getProcessingCodesForCombo()
        {
            List<IModel> models = new List<IModel>();

            hukpiDatabaseDataSetTableAdapters.ProcessingCodesTableAdapter processingCodesDataAdapter = new hukpiWinApp.hukpiDatabaseDataSetTableAdapters.ProcessingCodesTableAdapter();
            hukpiDatabaseDataSet.ProcessingCodesDataTable processingCodesData = processingCodesDataAdapter.GetData();

            models.Add(new Model(0, Properties.Settings.Default.ComboBoxNotSelected));

            string name;

            foreach (hukpiDatabaseDataSet.ProcessingCodesRow row in processingCodesData)
            {
                name = row["ProcessingCode"].ToString() + " - " + row["ProcessingName"].ToString();
                models.Add(new Model(getIntValueFromDB(row["ProcessingCodesId"]), name));
            }

            return models;
        }

        #endregion
    }

    public interface IModel
    {
        string Description { get; set; }
        int Id { get; set; }
    }

    public class Model : IModel
    {
        string description;
        int id;
        public string Description { get { return description; } set { description = value; } }
        public int Id { get { return id; } set { id = value; } }

        public Model(int id, string description)
        {
            this.Description = description;
            this.id = id;
        }

        public Model(string description)
        {
            this.Description = description;
        }
    }
}
