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

namespace GFATask
{
    [Browsable(false), ToolboxItem(false)]
    public partial class ucAdminApps : UserControl
    {
        public ImageList imageList = new ImageList();
        private int sortcolumn = 0;

        public ucAdminApps()
        {
            InitializeComponent();
            this.SetDefaultDesign();

            this.ContextMenuStrip = new ContextMenuStrip();
            this.ContextMenuStrip.Items.Add("Bearbeiten", null, SetEditableItem);
            this.ContextMenuStrip.Items.Add("Schnelles kopieren", null, FastCopyApp);
            this.ContextMenuStrip.Items.Add("Löschen", null, RemoveApp);
            lvApps.MouseDoubleClick += SetEditableItem;


            imageList.ImageSize = new Size(24,24);
            imageList.Images.Add("", new Bitmap(imageList.ImageSize.Width, imageList.ImageSize.Height));
            var files = XObjects.GetFiles(Paths.Icons.Directory, "*.png|*.jpg|*.ico|*.jpeg|*.bmp|*.gif");
            foreach (var file in files)
            {
                using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
                {
                    imageList.Images.Add(Path.GetFileName(file), Image.FromFile(fs.Name));
                }
            }
          
            lvApps.DoubleBuffer(true);
            lvApps.SmallImageList = lvApps.LargeImageList =  imageList;
            lvApps.Columns.Add("Name");
            lvApps.Columns.Add("ID");
            lvApps.Columns.Add("Gruppen");
            lvApps.Columns.Add("Symbol");
            lvApps.Columns.Add("Prototyp");
            lvApps.Columns.Add("AD Gruppen");
            lvApps.Columns.Add("Zuletzt geändert");
            lvApps.Columns.Add("Erstellt am");
            typeof(AppLists).GetProperties().Select(prop => (Models.AppList<Models.App>)prop.GetValue(typeof(AppLists))).ToList().ForEach(applist =>
            {
                if (applist.Apps != null && applist.Type != AppType.Citrix && applist.Type != AppType.Favorites)
                {
                    ListViewGroup group = new ListViewGroup(applist.Type.ToString(), applist.Type.ToString());
                    lvApps.Groups.Add(group);
                    lvApps.Items.AddRange(applist.Apps.Select(app =>
                    {
                        var ad_groups = app.ActiveDirectoryGroups == null ? new string[] { "Keine" } : app.ActiveDirectoryGroups;
                        var item = new ListViewItem(new string[] { app.Name, app.ID.ToString(), app.Group, app.Icon, app.Prototype == true ? "✓" : "❌", string.Join(",", ad_groups), app.LastModified.ToEuropeDateCulture(), app.Created.ToEuropeDateCulture() }, Path.GetFileName(app.Icon), group);
                        return item;
                    }).ToArray());
                }
            });

            lvApps.SortByColumn(sortcolumn);
            lvApps.ColumnClick += (sender, e) => sortcolumn = e.Column;
            lvApps.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
            lvApps.AutoFillColumn(lvApps.Columns.Count -1);
        }

        public void AddAppToList(AppType apptype, Models.App app)
        {
            AddAppToList(apptype.ToString(), app);
        }


        public void AddAppToList(string apptype, Models.App app)
        {
            ListViewGroup group = lvApps.Groups[apptype];
            var ad_groups = app.ActiveDirectoryGroups == null ? new string[] { "Keine" } : app.ActiveDirectoryGroups;
            var item = new ListViewItem(new string[] { app.Name, app.ID.ToString(), app.Group, app.Icon, app.Prototype == true ? "✓" : "❌", string.Join(",", ad_groups), app.LastModified.ToEuropeDateCulture(), app.Created.ToEuropeDateCulture() }, Path.GetFileName(app.Icon), group);
            lvApps.Items.Add(item);
        }

        public void ReplaceAppInList(AppType apptype, Models.App app)
        {
            ListViewGroup group = lvApps.Groups[apptype.ToString()];
            var ad_groups = app.ActiveDirectoryGroups == null ? new string[] { "Keine" } : app.ActiveDirectoryGroups;
            var lvitem = group.Items.Cast<ListViewItem>().First(item => int.Parse(item.SubItems[1].Text) == app.ID && item.Group.Name == apptype.ToString());
            lvApps.Items.Remove(lvitem);
            lvitem = new ListViewItem(new string[] { app.Name, app.ID.ToString(), app.Group, app.Icon, app.Prototype == true ? "✓" : "❌", string.Join(",", ad_groups), app.LastModified.ToEuropeDateCulture(), app.Created.ToEuropeDateCulture() }, Path.GetFileName(app.Icon), group);
            lvApps.Items.Add(lvitem);
            lvApps.Invalidate();
            lvApps.ListViewItemSorter = new ListViewItemComparer(sortcolumn);
        }

        public void ReplaceAppInList(string apptype, Models.App app)
        {
            this.ReplaceAppInList((AppType)Enum.Parse(typeof(AppType), apptype, true), app);
        }


        public void RemoveAppFromList(AppType apptype, Models.App app)
        {
            ListViewGroup group = lvApps.Groups[apptype.ToString()];
            ListViewItem lvitem = group.Items.Cast<ListViewItem>().ToList().Find(item => int.Parse(item.SubItems[1].Text) == app.ID);
            lvApps.Items.Remove(lvitem);
        }

        public void RemoveAppFromList(string apptype, Models.App app)
        {
            RemoveAppFromList((AppType)Enum.Parse(typeof(AppType), apptype, true), app);
        }

        private void RemoveApp(object sender, EventArgs e)
        {
            var lvitem = lvApps.SelectedItems[0];
            var msgbox = XObjects.MessageBox("Soll die App " + lvitem.Text + " wirklich gelöscht werden", NotifyButtons.YesNo, NotifyType.Message, new Size(200, 200), "App Löschen", null);
            if (msgbox.Result == DialogResult.Yes)
            {
                AppType apptype = (AppType)Enum.Parse(typeof(AppType), lvitem.Group.Name, true);
                Models.AppList<Models.App> applist = Accessor.GetAppList(apptype);
                Models.App app = applist.Apps.Find(listapp => listapp.ID == int.Parse(lvitem.SubItems[1].Text));
                Creator.RemoveApp(lvitem.Group.Name, app);
            }
        }


        private void abtnCreate_Click(object sender, EventArgs e)
        {
            Forms.AppCreator.ResetControls();
            Accessor.OpenForm("AppCreator");
        }

        private void FastCopyApp(object sender, EventArgs e)
        {
            var lvitem = lvApps.SelectedItems[0];
            if (lvitem != null)
            {
                string typefromgroup = Enum.Parse(typeof(AppType), lvitem.Group.Name, true).ToString();
                Models.AppList<Models.App> applist = (Models.AppList<Models.App>)typeof(AppLists).GetProperty(lvitem.Group.Name).GetValue(typeof(Models.AppList<Models.App>));
                Models.App app_copy = applist.Apps.Find(app => app.ID == int.Parse(lvitem.SubItems[1].Text)).Copy();
                app_copy.Name = app_copy.Name + " (Kopie " + applist.Apps.Count(app => app.Name == app_copy.Name) + ")";
                app_copy.ID = applist.Apps.Max(app => app.ID) + 1;
                app_copy.Created = DateTime.Now;
                app_copy.LastModified = DateTime.Now;
                Creator.AddApp(lvitem.Group.Name, app_copy);
            }
        }

        private void SetEditableItem(object sender, EventArgs e)
        {
            var item = lvApps.SelectedItems[0];
            if (item != null)
            {
                string typefromgroup = Enum.Parse(typeof(AppType), item.Group.Name, true).ToString();
                Models.AppList<Models.App> applist = (Models.AppList<Models.App>)typeof(AppLists).GetProperty(item.Group.Name).GetValue(typeof(Models.AppList<Models.App>));
                Models.App appitem = applist.Apps.Find(app => app.ID == int.Parse(item.SubItems[1].Text));
                Forms.AppCreator.GetEditableItem(applist.Type, appitem);
                Accessor.OpenForm("AppCreator", Forms.Administration);
            }
        }


        class ListViewItemComparer : IComparer
        {
            private int col;
            public ListViewItemComparer()
            {
                col = 0;
            }

            public ListViewItemComparer(int column)
            {
                col = column;
            }

            public int Compare(object x, object y)
            {
                return String.Compare(((ListViewItem)x).SubItems[col].Text, ((ListViewItem)y).SubItems[col].Text);
            }
        }
    }
}
