using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.DirectoryServices;
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 FormAppCreator : FormEx
    {
        public FormAppCreator()
        {
            InitializeComponent();
            this.ResetControls();
            cbAppType.Items.AddRange(Enum.GetNames(typeof(AppType)).Where(name => name != "None" || name != "Citrix").ToArray());

            if (!dgvExecutes.Columns.Contains("colBefehl")) dgvExecutes.Columns.Add("colBefehl", "Befehl");
            if (!dgvExecutes.Columns.Contains("colArgumente")) dgvExecutes.Columns.Add("colArgumente", "Argumente");
            this.Icon = Icon.FromHandle(new Bitmap(File.OpenRead(Paths.Icons.Directory + @"System\new.png")).GetHicon());
            this.DesktopAnchor = DesktopAnchor.Center;
            this.SetDefaultDesign();
            dgvExecutes.BackgroundColor = this.BackColor;
            dgvExecutes.DefaultCellStyle.BackColor = this.BackColor;
            dgvExecutes.EnableHeadersVisualStyles = false;
            dgvExecutes.RowHeadersDefaultCellStyle.BackColor = this.BackColor;
            dgvExecutes.DefaultCellStyle.ForeColor = this.ForeColor;
            dgvExecutes.DefaultCellStyle.Font = this.Font;
        }

        private void abtnCheckADGroupName_Click(object sender, EventArgs e)
        {
            rtbADGroups.Text.Split(';').ToList().ForEach(groupname =>
            {
                var settledgroupname = groupname.Replace(" ", "");
                if (ActiveDirectory.GroupExists(settledgroupname).Item1)
                    rtbADGroups.Text = rtbADGroups.Text.Replace(settledgroupname, ActiveDirectory.GroupExists(settledgroupname).Item2) + Environment.NewLine;
            });
        }

        /// <summary>
        /// Fügt den entsprechenden Steuerelementen die Informationen der App hinzu um diese editieren zu können
        /// </summary>
        /// <param name="app"></param>
        public void GetEditableItem(AppType apptype, Models.App app)
        {
            this.ResetControls();
            cbAppType.Text = apptype.ToString();
            lID.Text = app.ID.ToString();
            lIsNew.Text = string.Empty;
            tbAppname.Text = app.Name;
            tbDescription.Text = app.Description;
            tbGroup.Text = app.Group;
            switchPrototype.Checked = app.Prototype;
            if (apptype != AppType.Favorites)
            {
                labelPrototype.Visible = true;
                switchPrototype.Visible = true;
                rtbADGroups.Enabled = true;
                abtnCheckADGroupName.Enabled = true;
            }
            else
            {
                labelPrototype.Visible = false;
                switchPrototype.Checked = false;
                switchPrototype.Visible = false;
                rtbADGroups.Enabled = false;
                abtnCheckADGroupName.Enabled = false;
            }

            cbAppType.Enabled = false;
            if (app.ActiveDirectoryGroups != null)
                rtbADGroups.Text = string.Join("; ", app.ActiveDirectoryGroups);
            app.Execute.ToList().ForEach(exec =>
            {
                dgvExecutes.Rows.Add(exec.Command, exec.Args);
            });
            lIconPath.Tag = Cast.IconPath(apptype, app.Icon);
            lIconPath.Text = Path.GetFileName(app.Icon);
            if (File.Exists(lIconPath.Tag.ToString()))
            {
                using (FileStream fs = new FileStream(lIconPath.Tag.ToString(), FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
                {
                    picbox.Image = Image.FromStream(fs);
                }
            }
        }


        private void abtnIconPath_Click(object sender, EventArgs e)
        {
            var ofd = new OpenFileDialog() { Multiselect = false, Filter = "Image Files(.JPG; .JPEG; .JPE; .BMP; .GIF; .PNG)|*.JPG;*.JPEG;*.JPE;*.BMP;*.GIF;*.PNG" };
            if (lIconPath.Tag != null && lIconPath.Text != string.Empty)
                ofd.InitialDirectory = Path.GetDirectoryName(lIconPath.Tag.ToString());
            else
            {
                ofd.InitialDirectory = Paths.Icons.Directory;
                lIconPath.Text = "[Kein Symbol]";
            }

            if (ofd.ShowDialog(this) == DialogResult.OK)
            {
                lIconPath.Text = ofd.SafeFileName;
                lIconPath.Tag = ofd.FileName;
                using (FileStream fs = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
                {
                   picbox.Image = Image.FromStream(fs);
                }
            }
        }

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


        public void ResetControls()
        {
            labelPrototype.Visible = true;
            switchPrototype.Visible = true;
            lIsNew.Text = "[Neu]";
            lID.Text = string.Empty;
            tbAppname.Clear();
            tbDescription.Clear();
            tbGroup.Clear();
            cbAppType.Enabled = true;
            switchPrototype.Checked = true;
            cbAppType.Text = string.Empty;
            rtbADGroups.Clear();
            dgvExecutes.Rows.Clear();
            picbox.Image = new Bitmap(picbox.Width, picbox.Height);
            lIconPath.Text = "[Kein Symbol]";
        }

        private void abtnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void abtnSave_Click(object sender, EventArgs e)
        {
            if (cbAppType.Text == "")
            {
                XObjects.MessageBox("App Liste auswählen", NotifyButtons.OK, NotifyType.Message, new Size(125, 100), "App Liste", null);
            }
            else
            {
                Models.AppList<Models.App> applist = Accessor.GetAppList(cbAppType.Text);
                // Ersetzt vorhandene App 
                if (int.TryParse(lID.Text, out _) && applist.Apps.Exists(app => app.ID == int.Parse(lID.Text)))
                {
                    Models.App appitem = applist.Apps.Find(app => app.ID == int.Parse(lID.Text)).Copy();
                    appitem.Name = tbAppname.Text;
                    appitem.Group = tbGroup.Text;
                    appitem.Description = tbDescription.Text;
                    appitem.Prototype = switchPrototype.Checked;
                    appitem.ActiveDirectoryGroups = rtbADGroups.Text.Split(';').Length == 0 || rtbADGroups.Text == "" ? null : rtbADGroups.Text.Split(';');
                    appitem.Execute = dgvExecutes.Rows.Cast<DataGridViewRow>().Where(row => !row.IsNewRow).Select(row =>
                            new Models.Execute()
                            {
                                Command = row.Cells[0].Value == null ? null : row.Cells[0].Value.ToString(),
                                Args = row.Cells[1].Value == null ? null : row.Cells[1].Value.ToString()
                            }).ToArray();
                    if(lIconPath.Text != string.Empty)
                    {
                        if((AppType)Enum.Parse(typeof(AppType), cbAppType.Text, true) == AppType.Favorites)
                        {
                            if (lIconPath.Tag.ToString() != Cast.IconPath(AppType.Favorites, lIconPath.Text))
                                Creator.StreamCopy(lIconPath.Tag.ToString(), Cast.IconPath(AppType.Favorites, lIconPath.Text), null);
                        }
                        else
                        {
                            if (lIconPath.Tag != null && !File.Exists($"{Paths.Icons.Directory}{lIconPath.Text}") && File.Exists(lIconPath.Tag.ToString()))
                                Creator.StreamCopy(lIconPath.Tag.ToString(), $"{Paths.Icons.Directory}{lIconPath.Text}", (fs) =>
                                {
                                    Forms.Administration.UcAdminApps.imageList.Images.Add(Path.GetFileName(fs.Name), Image.FromStream(fs));
                                });
                        }
                        appitem.Icon = lIconPath.Text;
                    }
                    Creator.ReplaceApp(cbAppType.Text, appitem);
                }
                else
                {
                    // Erstellt neue App
                    Models.App app_new = new Models.App()
                    {
                        ID = applist.Apps.Max(app => app.ID) + 1,
                        Name = tbAppname.Text,
                        Description = tbDescription.Text,
                        Group = tbGroup.Text,
                        Icon = lIconPath.Text,
                        Created = DateTime.Now,
                        LastModified = DateTime.Now,
                        Prototype = switchPrototype.Checked,
                        ActiveDirectoryGroups = rtbADGroups.Text.Split(';').Length == 0 ? null : rtbADGroups.Text.Split(';'),
                        Execute = dgvExecutes.Rows.Cast<DataGridViewRow>().Where(row => !row.IsNewRow).Select(row =>
                                new Models.Execute()
                                {
                                    Command = row.Cells[0].Value == null ? null : row.Cells[0].Value.ToString(),
                                    Args = row.Cells[1].Value == null ? null : row.Cells[1].Value.ToString()
                                }).ToArray()
                    };


                    if (lIconPath.Tag != null && !File.Exists($"{Paths.Icons.Directory}{lIconPath.Text}"))
                        Creator.StreamCopy(lIconPath.Tag.ToString(), $"{Paths.Icons.Directory}{lIconPath.Text}", (fs) =>
                        {
                            Forms.Administration.UcAdminApps.imageList.Images.Add(Path.GetFileName(fs.Name), Image.FromStream(fs));
                        });
                    //File.Copy(lIconPath.Tag.ToString(), $"{Paths.Icons.Directory}{lIconPath.Text}", true);

                    Creator.AddApp(cbAppType.Text, app_new);
                }


                this.ResetControls();
                this.Close();
            }
           
        }

        private void picbox_Paint(object sender, PaintEventArgs e)
        {
            
        }

        private void cbAppType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(this.Created)
            {
                lID.Text = (Accessor.GetAppList(cbAppType.Text).Apps.Max(app => app.ID) + 1).ToString();
                rtbADGroups.Enabled = cbAppType.Text != AppType.Favorites.ToString();
            }
        }
    }
}
