using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.DirectoryServices.AccountManagement;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GFATask
{
     
    public partial class FormGroups : FormEx
    {
        public FormGroups()
        {
            InitializeComponent();

            lvGroups.DoubleBuffer(true);
            // Lädt das Layout des GFATask 
            this.SetDefaultDesign();
            lvGroups.SortByColumn(0);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            lLoading.ForeColor = Coloring.GetReadableForeColor(lLoading.BackColor);

        }

        public void AddADGroup(GroupPrincipal group)
        {
            var item = new ListViewItem(new string[] { group.Name, group.Sid.Value, group.Description });
            var subSID = new ListViewItem.ListViewSubItem(item, group.Sid.Value);
            var subDescription = new ListViewItem.ListViewSubItem(item, group.Description);
            item.SubItems.AddRange(new ListViewItem.ListViewSubItem[] { subSID, subDescription });

            if (lvGroups.InvokeRequired)
            {
                lvGroups.Invoke(new MethodInvoker(delegate
                {
                    lvGroups.Items.Add(item);
                    lvGroups.Update();
                    lvGroups.Invalidate();
                }));
            }
            else
            {
                lvGroups.Items.Add(item);
                lvGroups.Update();
                lvGroups.Invalidate();
            }
        }


        /// <summary>
        /// Durchsucht die Domäne nach Active Directory Gruppen
        /// </summary>
        /// <param name="local">Befindet sich der PC in einer Domäne, dann false, andernfalls true</param>
        public void Loading(bool local = false)
        {
            if (lvGroups.InvokeRequired)
            {
                lvGroups.Invoke(new MethodInvoker( delegate { lvGroups.Items.Clear(); }));
            }
            else
            {
                lvGroups.Items.Clear();
            }
            if (!local)
            {
                lLoading.Loading("Suche nach Gruppen", "Suche abgeschlossen", AD.GetGroups);
            }
            else
                lLoading.Loading("Suche nach Gruppen", "Keine Domäne gefunden", null);
        }


        protected override void OnClosing(CancelEventArgs e)
        {
            this.Visible = false;
            e.Cancel = true;
            base.OnClosing(e);
        }

        private void abtnRefresh_Click(object sender, EventArgs e)
        {
            lvGroups.Items.Clear();
            this.Loading();
        }
    }
}
