using System;
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
{
    public partial class FormAppButtonGroup : FormEx
    {
        private GroupButton _mygroupbutton = null;
        public GroupButton MyGroupButton
        {
            get => _mygroupbutton;
            set
            {
                _mygroupbutton = value;
                _apptype = _mygroupbutton.AppType;
            }
        }


        private AppType _apptype;
        public AppType AppType { get => _apptype; set => _apptype = value; }


        public FormAppButtonGroup()
        {
            InitializeComponent();
        }


        protected override void OnVisibleChanged(EventArgs e)
        {
            if (this.Visible)
            {
                flpAppbuttons.Controls.AddRange(_mygroupbutton.ContainedAppButtons.ToArray<Control>());
                Comparer.SortAllButtons(flpAppbuttons.Controls, Config.User.Prevalence);
                this.Sizing();
                this.SetDefaultDesign();
            }
            else
            {
                flpAppbuttons.Controls.Clear();
            }
            base.OnVisibleChanged(e);
           
        }


        public void Sizing()
        {
            if (_mygroupbutton != null)
            {
                int appcounts = _mygroupbutton.ContainedAppButtons.Where(appbutton => appbutton.Visible).ToList().Count;
                int columns = Config.User.GroupListColumnCount;
                int border = this.Padding.Horizontal;
                int vborder = this.Padding.Vertical;
                Size appsize = new Size((Config.User.Apps.ImageOnly ? Config.User.Apps.Size.Height : Config.User.Apps.Size.Width) + (Config.User.Apps.Margin * 2), Config.User.Apps.Size.Height + (Config.User.Apps.Margin * 2));

                int width, height;

                width = (appsize.Width * (appcounts < columns ? appcounts : columns)) < ((TextRenderer.MeasureText(this.Text, this.Font).Width + (this.TitlebarHeight * 4) + this.Icon.Size.Width) / appsize.Width) * appsize.Width ?
                            (((TextRenderer.MeasureText(this.Text, this.Font).Width + (this.TitlebarHeight * 4) + this.Icon.Size.Width) / appsize.Width) * appsize.Width) + border :
                            (appsize.Width * (appcounts < columns ? appcounts : columns)) + border;

                height = (((int)Math.Ceiling((appsize.Width * appcounts) / (double)width)) * appsize.Height) + vborder;
                this.Size = new Size(width, height);
            }
        }

        /// <summary>
        /// Löscht einen AppButton aus einem AppListPanel anhand des Apptypen und der App aus der JSON-Datei
        /// </summary>
        /// <param name="apptype">Findet anhand des Typen das gewünschte AppListPanel</param>
        /// <param name="app">Die JSON-App mit der der AppButton gefunden und entfernt wird</param>
        public void RemoveButton(Models.App app)
        {
            try
            {
                if (_mygroupbutton != null)
                {

                    if (flpAppbuttons.Controls.ContainsKey(app.ID + "_" + _apptype.ToString() + "_" + app.Name))
                    {
                        Control appbutton = flpAppbuttons.Controls.Find(Cast.AppButtonName(_apptype, app), false)[0];
                        flpAppbuttons.Controls.Remove(appbutton);
                        _mygroupbutton.ContainedApps.Remove(app);
                        _mygroupbutton.ContainedAppButtons.Remove(appbutton as AppButton);
                        //if(_mygroupbutton.ContainedApps.Exists(_app => _app.ID == app.ID))
                        //    _mygroupbutton.ContainedAppButtons.Remove((AppButton)appbutton);
                    }

                    if (_mygroupbutton.ContainedAppButtons.Count <= 1 && flpAppbuttons.Controls.Count > 0)
                    {
                        AppListPanel panel = Accessor.GetAppListPanel(_apptype);
                        panel.RemoveGroupButton(_mygroupbutton.Name);
                        this.Close();
                    }
                    else
                    {
                        this.Sizing();
                    }
                }
            }
            catch (Exception ex)
            {
                Log.EventLog.Write("FormAppButtonGroup RemoveButton-Fehler", LogClassification.CriticalError, ex);
            }
        }


        public bool ReplaceButton(Models.App replacing_app) => 
            this.ReplaceButton(_apptype, replacing_app);      


        public bool ReplaceButton(AppType apptype, Models.App replacing_app)
        {
            if (apptype == AppType.None)
                return false;
            Models.App existing_app = Accessor.GetAppList(apptype).Apps.Find(app => app.ID == _mygroupbutton.ContainedAppButtons.ToList().Find(button => button.Name == Cast.AppButtonName(apptype, replacing_app)).ID);
            if (existing_app != null)
            {
                AppButton appbutton = _mygroupbutton.ContainedAppButtons.Select(button => button).ToList().Find(button => button.Name == Cast.AppButtonName(apptype, existing_app));
                int cur_index = _mygroupbutton.ContainedAppButtons.ToList().IndexOf(appbutton);
                appbutton.Name = Cast.AppButtonName(apptype, replacing_app);
                appbutton.Text = replacing_app.Name;
                appbutton.ActiveDirectoryGroups = replacing_app.ActiveDirectoryGroups;
                appbutton.Prevalence = Accessor.GetPrevalencia(apptype, replacing_app.ID);
                appbutton.Execute = replacing_app.Execute;
                appbutton.Visible = Cast.AppVisibility(replacing_app);
                appbutton.Image = Image.FromStream(File.OpenRead(Cast.IconPath(apptype, replacing_app.Icon)));
                _mygroupbutton.ContainedAppButtons[cur_index] = appbutton;
                Comparer.SortAllButtons(flpAppbuttons.Controls, Config.User.Prevalence);
                return true;
            }
            return false;
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            this.Visible = false;
            e.Cancel = e.CloseReason == CloseReason.UserClosing;
            base.OnFormClosing(e);
        }
    }
}
