using log4net;
using log4net.Config;
using Org.BouncyCastle.Cms;
using Org.BouncyCastle.Utilities;
using Renci.SshNet;
using Renci.SshNet.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.InteropServices; // for moving console window
using System.Runtime.Remoting.Contexts;
using System.Security.Cryptography;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace FHT
{


    public partial class TastList : Form
    {
        // set to false to enable Encrypt , Decrypt Buttons
        public const bool IsAdminDisabled = false;
        
        
        public List<cTask> Tasks = new List<cTask>();
        public cConInfo conInfo = new cConInfo("", "", "", "", "", "");
        private List<Profile> Profiles = new List<Profile>();
        public static ILog log = LogManager.GetLogger(typeof(Program));
        private int RowToDrag = -1; //for arrange tasks
        private int RowToDrop = -1; // for arrange tasks
        private string Tasklistfilename = "tasklist.json";
        private string Profilefilename = "profile.json";
        private bool bEncryption = true;
        private static Aes aes ;
        private static Utilities utilities = new Utilities(log);

        //for moving console window
        // Import the necessary Windows API functions
        [DllImport("kernel32.dll", SetLastError = true)]
        static extern IntPtr GetConsoleWindow();

        [DllImport("user32.dll", SetLastError = true)]
        internal static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetForegroundWindow(IntPtr hWnd);

        public TastList()
        {
            this.StartPosition = FormStartPosition.Manual;
            this.Location = new Point(100,100);

            var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
            log4net.Util.LogLog.InternalDebugging = true;
            XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));

            InitializeComponent();

            //encryption
            aes = Aes.Create();

            

            //set default tasklist file 
            openFileDialogTasklist.InitialDirectory = System.IO.Directory.GetCurrentDirectory();
            openFileDialogTasklist.FileName = Tasklistfilename;
            buttonTasklistPath.Text = Tasklistfilename;


            // set Tooltip
            toolTipbuttonTasklist.ToolTipTitle = "Task List and Profile";
            toolTipbuttonTasklist.SetToolTip(buttonTasklistPath, " Pick another, the default is tasklist.json");
            toolTipbuttonTasklist.SetToolTip(buttonLoad, " Load or reload task list file");
            toolTipbuttonTasklist.SetToolTip(buttonSave, "Save the current task list file");
            toolTipbuttonTasklist.SetToolTip(buttonAESString, " Input or change EAS string");

            toolTipGeneralConf.ToolTipTitle = "Configuration";
            toolTipGeneralConf.SetToolTip(buttonConf, " Configure TFTP, Encrypion and more");

     



            //move console window
            int newX = this.Right; // to right size of the main form
            int newY = this.Top; // align top
            int NewWidth = 400;
            int NewHeight = this.Height;

            IntPtr consoleHandle = GetConsoleWindow();

            if (consoleHandle != IntPtr.Zero)
            {
                
                
                                
                bool success = MoveWindow(consoleHandle, newX, newY, NewWidth, NewHeight, true);

                if (success)
                {
                    Console.WriteLine($"Console to ({newX}, {newY}).");
                }
                else
                {
                    Console.WriteLine("Failed to move console.");
                }

                SetForegroundWindow(consoleHandle);
            }
            else
            {
                Console.WriteLine("Failed get console window handle.");
            }
            

            //Initialize Gridview behaviours 
            dataGridViewTask.AllowDrop = true;
            dataGridViewTask.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText;
            dataGridViewTask.RowTemplate.ContextMenuStrip = contextMenuStripRow;

            //ask for AES key
            buttonAESString_Click(null, null);

            //Load Profile list from "Profilefilename"
            Profiles = utilities.LoadProfile(Profilefilename, aes);

            if (!Profiles.Any())
            {
                //load "do nothing" to Profiles
                Profile temp = new Profile();
                temp.ProfileType = "";
                temp.ProfileName = "Do nothing";
                temp.ProfileCommands = new string[] { "echo  Do nothing" };
                temp.ProfileParameters = new string[] { "" };

                Profiles.Add(temp);
            }

            try
            {
                foreach (Profile p in Profiles)
                {
                    log.Info(string.Format("Profile: {0}", p.ProfileName));
                }

                var comboBoxColumn = (DataGridViewComboBoxColumn)dataGridViewTask.Columns[7];
                comboBoxColumn.DataSource = Profiles; // Set the data source of the ComboBox column
                comboBoxColumn.DisplayMember = "profileName"; // Displayed property name
                comboBoxColumn.ValueMember = "profileName"; //The property name of the value
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }

            dataGridViewTask.Refresh();

        }

        private void fSSHTest_Load(object sender, EventArgs e)
        {
        }

        private void bRun_Click(object sender, EventArgs e)
        {
            //Disable Arrange Tasks first
            checkBoxArrangeTask.Checked = false;
            log.Info("Run selected Tasks was called");
            string listofruntasks = "Task(s) ran: \n";
            foreach (DataGridViewRow row in dataGridViewTask.Rows)
            {
                Profile profile;
                DataGridViewCheckBoxCell cell = row.Cells[4] as DataGridViewCheckBoxCell;
                log.Info(string.Format("Test if task is checked: task {0}", row.Index));

                if (cell.Value != null)
                {
                    if ((bool)cell.Value == true)
                    {
                        log.Info(string.Format("Run selected Tasks: task {0}", row.Index));
                        var currentTask = Tasks[row.Index];
                        try
                        {
                            profile = Profiles.Find(x => x.ProfileName == currentTask.sProfile.ToString());


                            // print out task
                            log.Info(string.Format("Current task profile {0}:", currentTask.sTaskDevice.ToString()));

                            foreach (string c in profile.ProfileCommands)
                                log.Info(c);


                            //check if task has parameters and get parameters list
                 

                            if (profile.ProfileParameters.Length > 0)
                            {
                                //Get Values for Parameters
                                FormParameters formParameter = new FormParameters(currentTask.dParameters, richTextBoxOutput.Text, 
                                    string.Format("{0}: {1}", currentTask.sTaskDescription, currentTask.sProfile));
                                
                                    
                                if (formParameter.ShowDialog() == DialogResult.Cancel)
                                {
                                    log.Info("formParameter returns with Cancel");
                                    break;
                                }


                                //foreach (var c in currentTask.dParameters)
                                //    log.Info(string.Format("Parameter {0}: {1}", c.Key, c.Value));
                            }

                            //clear richtextboxoutput
                            //richTextBoxOutput.Clear();


                            // insert task name to listofruntasks
                            listofruntasks += string.Format(" Task {0}: {1}, profile: {2} \n", currentTask.iTaskNum, currentTask.sTaskDescription, currentTask.sProfile);
                            // Run a Task and display result on the textbox
                            richTextBoxOutput.AppendText(Utilities.RunaTask(currentTask, profile, conInfo,aes));
                            richTextBoxOutput.SelectionStart = richTextBoxOutput.Text.Length;
                            richTextBoxOutput.ScrollToCaret();
                            
                            

                        }
                        catch
                        {
                            log.Error("Can not load profile or Profile is empty");
                        }

                        //update Status LastRun
                        string ttt = DateTime.Now.ToString(("HH:mm:ss"));
                        dataGridViewTask.Rows[row.Index].Cells[6].Value = ttt;

                    }



                }
                

            }
            
            //dump output to file.txt
            string filepath = string.Format("{0}\\{1}\\{2}_{3}.txt", Environment.CurrentDirectory,
                Environment.MachineName, Environment.MachineName, DateTime.Now.ToString("yyyyMMdd_HHmmss"));
            try
            {
                
                string dir = Path.GetDirectoryName(filepath);
                // Create the directory 
                
                if (!string.IsNullOrEmpty(dir))
                {
                    Directory.CreateDirectory(dir);
                }
              
                File.WriteAllText(filepath, listofruntasks);
                File.AppendAllText(filepath, richTextBoxOutput.Text.ToString());
                log.Info(string.Format("Wrote to file: {0}", filepath));
            }
            catch (Exception ex)
            {
                log.Info($"An error occurred: {ex.Message}");
            }

            log.Info("Run selected Tasks End");
        }


        private void buttonTasklistPath_Click(object sender, EventArgs e)
        {
            if (openFileDialogTasklist.ShowDialog() == DialogResult.OK)
            {
                Tasklistfilename = openFileDialogTasklist.FileName;
                buttonTasklistPath.Text = openFileDialogTasklist.SafeFileName;

                //load tasklist 
                buttonLoad_Click(null,null);
            }
        }
        private void buttonSave_Click(object sender, EventArgs e)
        {
            //Disable Arrange Tasks first
            checkBoxArrangeTask.Checked = false;

            if (Tasks.Count >= 1)
            {
                utilities.SaveTasklist(Tasks, Tasklistfilename, aes);
            }
        }

        private void buttonLoad_Click(object sender, EventArgs e)
        {


            //Disable Arrange Tasks first
            checkBoxArrangeTask.Checked = false;

            Tasks = utilities.LoadTaskList(Tasklistfilename, aes);

            //clear TaskList
            dataGridViewTask.Rows.Clear();

            foreach (var task in Tasks)
            {
                try
                {
                    DataGridViewRow row = (DataGridViewRow)dataGridViewTask.Rows[0].Clone();
                    row.Cells[0].Value = task.iTaskNum;
                    row.Cells[1].Value = task.sTaskDescription;
                    row.Cells[2].Value = task.sTaskDevice;
                    row.Cells[4].Value = task.bTaskSelect;
                    // var comboBoxColumn = (DataGridViewComboBoxColumn)dataGridViewTask.Columns[7];
                    // test if task.sprofile name mach any in Profiles, if true, assign that name 
                    if (Profiles.Any(pr => pr.ProfileName == task.sProfile))
                        row.Cells[7].Value = task.sProfile;
                    else
                        row.Cells[7].Value = null;
                    dataGridViewTask.Rows.Add(row);
                }
                catch (Exception ex)
                {
                    log.Error(string.Format("Error while loading saved tasklist: \n {0}", ex.Message));
                }


            }
        }

        private void buttonConf_Click(object sender, EventArgs e)
        {
            FormConfiguration formConfiguration = new FormConfiguration(conInfo.sTftpIP, conInfo.sSftpIP, 
                conInfo.sSftpUsername, conInfo.sSftpPassword, 
                bEncryption, aes, Profilefilename,log);
            // Disable Encrypt, Decrypt buttons
            if(IsAdminDisabled)
            {
                formConfiguration.AdminDisable();
            }
            formConfiguration.ShowDialog();
            //reload profile and task list
            Profilefilename = formConfiguration.sProfilePath;
            //try reloading Profilefilename
            Profiles.Clear();
            Profiles = utilities.LoadProfile(Profilefilename, aes);

            // Configure Profile list to dropdown menu, first to check if profiles is empty
            if (!Profiles.Any())
            {
                //load "do nothing" to Profiles
                Profile temp = new Profile();
                temp.ProfileType = "";
                temp.ProfileName = "Do nothing";
                temp.ProfileCommands = new string[] { "echo  Do nothing" };
                temp.ProfileParameters = new string[] { "" };

                Profiles.Add(temp);
            }

            try
            {
                foreach (Profile p in Profiles)
                {
                    log.Info(string.Format("Profile: {0}", p.ProfileName));
                }

                var comboBoxColumn = (DataGridViewComboBoxColumn)dataGridViewTask.Columns[7];
                comboBoxColumn.DataSource = Profiles; // Set the data source of the ComboBox column
                comboBoxColumn.DisplayMember = "profileName"; // Displayed property name
                comboBoxColumn.ValueMember = "profileName"; //The property name of the value
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
            

            
            
            //reload tasklist
            
            buttonLoad_Click(null, null);

            conInfo.sTftpIP = formConfiguration.Tftp_IP;
            conInfo.sSftpIP = formConfiguration.Sftp_IP;
            conInfo.sSftpUsername = formConfiguration.Sftp_Username;
            conInfo.sSftpPassword = formConfiguration.Sftp_Password;

            dataGridViewTask.Refresh();

        }

        private void dataGridViewTask_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            // Ensure the click is on a valid celland not in arrange mode and not the header and start edit mode immediately
            if ((!checkBoxArrangeTask.Checked) && (e.RowIndex >= 0) && (e.ColumnIndex > 0))
            {
                // Set the cell as the current cell (if not already)
                dataGridViewTask.CurrentCell = dataGridViewTask.Rows[e.RowIndex].Cells[e.ColumnIndex];


                dataGridViewTask.BeginEdit(true);
            }
        }

        private void dataGridViewTask_CellToolTipTextNeeded(object sender, DataGridViewCellToolTipTextNeededEventArgs e)
        {
            //show tool tips for cells in Run column 5
            log.Info("Handle showing tooltip at a cell");
            if (e.ColumnIndex == 5)
            {
                e.ToolTipText = string.Format("Run Task {0}: {1}", dataGridViewTask.Rows[e.RowIndex].Cells[1], dataGridViewTask.Rows[e.RowIndex].Cells[2]);
            }
        }

        private void buttonCheckAll_Click(object sender, EventArgs e)
        {
            //Disable Arrange Tasks first
            checkBoxArrangeTask.Checked = false;

            foreach (DataGridViewRow row in dataGridViewTask.Rows)
            {
                DataGridViewCheckBoxCell cell = row.Cells[4] as DataGridViewCheckBoxCell;

                if (cell.Value != null)
                {                    
                    cell.Value = true;
                    Tasks[row.Index].bTaskSelect = true; 
                }
            }
            dataGridViewTask.Refresh();
        }

        private void buttonUncheckAll_Click(object sender, EventArgs e)
        {
            //Disable Arrange Tasks first
            checkBoxArrangeTask.Checked = false;

            foreach (DataGridViewRow row in dataGridViewTask.Rows)
            {
                DataGridViewCheckBoxCell cell = row.Cells[4] as DataGridViewCheckBoxCell;

                if (cell.Value != null)
                {
                    cell.Value = false;
                    Tasks[row.Index].bTaskSelect = false;
                }
            }
            dataGridViewTask.Refresh();
        }

        private void checkBoxArrangeTask_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBoxArrangeTask.Checked)
            {
                dataGridViewTask.AllowUserToAddRows = false;
                // change mouse cursor to Hand
                dataGridViewTask.Cursor = System.Windows.Forms.Cursors.Hand;
                

            }
            else
            {
                dataGridViewTask.AllowUserToAddRows = true;
                // change mouse cursor back to Default
                dataGridViewTask.Cursor = System.Windows.Forms.Cursors.Default;

            }

        }

        private void dataGridViewTask_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

            Profile profile;

            try
            {
                var currentTask = Tasks[e.RowIndex];

                //currentTask.dParameters = new Dictionary<string, string>();

                switch (e.ColumnIndex)
                {
                    case 4: //"select" Column

                        break;

                    case 5: //"Run" was clicked at a task

                        try
                        {
                            profile = Profiles.Find(x => x.ProfileName == currentTask.sProfile.ToString());

                            if (profile !=null && profile.ProfileName != "Do nothing")
                            {
                                // print out task
                                log.Info(string.Format("Current task profile {0}:", currentTask.sTaskDevice.ToString()));

                                foreach (string c in profile.ProfileCommands)
                                    log.Info(c);
                                if (profile.ProfileParameters.Length > 0)
                                {
                                    //Get Values for Parameters
                                    FormParameters formParameter = new FormParameters(currentTask.dParameters, richTextBoxOutput.Text,
                                        string.Format("{0}: {1}", currentTask.sTaskDescription, currentTask.sProfile));
                                    if (formParameter.ShowDialog() == DialogResult.Cancel)
                                    {
                                        log.Info("formParameter returns with Cancel");
                                        break;
                                    }

                                    //foreach (var c in currentTask.dParameters)
                                    //    log.Info(string.Format("Parameter {0}: {1}", c.Key, c.Value));
                                }

                                //clear richtextboxoutput
                                richTextBoxOutput.Clear();

                                // Run a Task and display result on the textbox

                                richTextBoxOutput.AppendText(Utilities.RunaTask(currentTask, profile, conInfo, aes));
                                richTextBoxOutput.SelectionStart = richTextBoxOutput.Text.Length;
                                richTextBoxOutput.ScrollToCaret();
                                //update Status LastRun
                                string ttt = DateTime.Now.ToString(("HH:mm:ss"));
                                dataGridViewTask.Rows[e.RowIndex].Cells[6].Value = ttt;
                            }
                            else
                                log.Info("Profile = Null");                            
                            
                        }
                        catch
                        {
                            log.Error("Can not load profile or Profile is empty");
                        }
                        break;

                    case 6: //call Parameters

                        FormCredential formCredential = new FormCredential("", "");
                        formCredential.ShowDialog();


                        break;

                    case 7: //select profile


                        break;

                    default:
                        break;

                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void dataGridViewTask_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            Profile profile = new Profile();
            if (e.ColumnIndex != 5)
            {
                if (Tasks.Count < (e.RowIndex + 1))
                {
                    Tasks.Add(new cTask(e.RowIndex + 1, "", "", false, ""));
                    Tasks[e.RowIndex].iTaskNum = e.RowIndex + 1;
                    dataGridViewTask.Rows[e.RowIndex].Cells[0].Value = e.RowIndex + 1;
                    dataGridViewTask.Rows[e.RowIndex].Cells[5].Value = Properties.Resources.Run16b;
                    dataGridViewTask.Rows[e.RowIndex].Cells["Profile"].Value = "Do nothing";
                    dataGridViewTask.Refresh();

                }
                switch (e.ColumnIndex)
                {
                    case 0:

                        break;
                    case 1:
                        if (dataGridViewTask.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null)
                        {
                            dataGridViewTask.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";                            
                        }
                        Tasks[e.RowIndex].sTaskDescription = (string)dataGridViewTask.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;

                        break;
                    case 2:
                        Tasks[e.RowIndex].sTaskDevice = (string)dataGridViewTask.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
                        break;
                    case 3:

                        break;
                    case 4:
                        if ((string)dataGridViewTask.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
                            Tasks[e.RowIndex].bTaskSelect = (bool)dataGridViewTask.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
                        break;
                    case 5:

                        break;
                    case 7:  // Profile
                        //assign default "Do nothing" to the new created task
                        if ((string)dataGridViewTask.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
                            Tasks[e.RowIndex].sProfile = (string)dataGridViewTask.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
                        else
                            Tasks[e.RowIndex].sProfile = "Do nothing";
                        if (!Profiles.Any())
                        {
                            profile = Profiles.Find(x => x.ProfileName == Tasks[e.RowIndex].sProfile.ToString());
                            if ((profile != null) && (profile.ProfileParameters.Length > 0))
                            {
                                //clear task profile parameters first
                                Tasks[e.RowIndex].dParameters.Clear();
                                //add new parameters
                                foreach (string c in profile.ProfileParameters)
                                {
                                    Tasks[e.RowIndex].dParameters.Add(c, "");
                                }
                            }
                        }
                        

                        log.Info(string.Format("Task {0}, profile {1}", e.RowIndex, Tasks[e.RowIndex].sProfile));

                        break;
                    default:

                        break;
                }


            }
        }

        private void dataGridViewTask_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {

     

            if (checkBoxArrangeTask.Checked)
            {
                // start "drag" handle with mouse left click
                if (e.Button == MouseButtons.Left)
                    if (e.RowIndex >= 0)
                    {
                        RowToDrag = e.RowIndex;
                        // start to catch "drag"                
                        dataGridViewTask.DoDragDrop(dataGridViewTask.Rows[e.RowIndex], DragDropEffects.Move);

                        // move focus to Dropped Cell
                        dataGridViewTask.CurrentCell = dataGridViewTask.Rows[RowToDrop].Cells[e.ColumnIndex];
                        dataGridViewTask.Rows[RowToDrop].Cells[e.ColumnIndex].Selected = true;
                        return;
                        
                    }
            }


            // right click , prep for delete, move cells

            if (e.Button == MouseButtons.Right)
            {
                
                //select the first cell of the row 

                if (e.RowIndex >= 0)
                {
                    //MessageBox.Show(string.Format("Row {0}, Column {1}", e.RowIndex, e.ColumnIndex));

                    if (dataGridViewTask.Rows.Count > 0)
                    //if (e.ColumnIndex == 0)
                    {
                        //check if anycell is in edit mode and exit edit mode
                        if (dataGridViewTask.IsCurrentCellInEditMode)
                        {
                            dataGridViewTask.CancelEdit();
                            dataGridViewTask.CurrentCell = null;
                        }

                        // Clear any previous selection
                        dataGridViewTask.ClearSelection();

                        // Select the first cell of the row
                        dataGridViewTask.CurrentCell = dataGridViewTask.Rows[e.RowIndex].Cells[0];
                        dataGridViewTask.Rows[e.RowIndex].Cells[0].Selected = true;
                        
                        //dataGridViewTask.CurrentCell = dataGridViewTask.Rows[e.RowIndex].Cells[1];
                    }

                }
            }
        }
     
        private void dataGridViewTask_DragEnter(object sender, DragEventArgs e)
        {
            if (checkBoxArrangeTask.Checked)
            {
                if (e.Data.GetDataPresent(typeof(DataGridViewRow)))
                {
                    e.Effect = DragDropEffects.Move;
                }
                else
                {
                    e.Effect = DragDropEffects.None;
                }
            }
        }

  
        private void dataGridViewTask_DragDrop(object sender, DragEventArgs e)
        {
            if (checkBoxArrangeTask.Checked)
            {
                if (e.Data.GetData(typeof(DataGridViewRow)) is DataGridViewRow rowToMove)
                {
                    Point clientPoint = dataGridViewTask.PointToClient(new Point(e.X, e.Y));
                    DataGridView.HitTestInfo hitpoint = dataGridViewTask.HitTest(clientPoint.X, clientPoint.Y);
                    

                    if (hitpoint.Type == DataGridViewHitTestType.Cell)
                    {
                        RowToDrop = hitpoint.RowIndex;

                        if (RowToDrag != RowToDrop)
                        {
                            // Remove the row 
                            dataGridViewTask.Rows.RemoveAt(RowToDrag);
                            
                            // Insert the row 
                            dataGridViewTask.Rows.Insert(RowToDrop, rowToMove);
                            // move Task in Tasks
                            cTask data = Tasks[RowToDrag];
                            Tasks.RemoveAt(RowToDrag);
                            Tasks.Insert(RowToDrop, data);                                                                                

                            // regenerate Task Num
                            RegenerateTaskNum();
                        }
                    }
                    RowToDrag = -1; // Reset 
                }
            }
        }

        private void MoveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            checkBoxArrangeTask.Checked = !checkBoxArrangeTask.Checked;
        }

        private void DeleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dataGridViewTask.SelectedCells.Count > 0)
            {
                if(dataGridViewTask.CurrentRow.Index < (dataGridViewTask.Rows.Count -1) ) // check if the Row to be deleted exists.
                    if ( MessageBox.Show(string.Format("Remove Task: {0} ?", dataGridViewTask.CurrentRow.Cells[0].Value),
                        "Confirm to Delete Task", MessageBoxButtons.YesNo,MessageBoxIcon.Question) == DialogResult.Yes) 
                    {
                        Tasks.RemoveAt(dataGridViewTask.CurrentRow.Index);
                        dataGridViewTask.Rows.RemoveAt(dataGridViewTask.CurrentRow.Index);
                        dataGridViewTask.Refresh();
                        RegenerateTaskNum();
                    }
                
            }
        }

        private void RegenerateTaskNum()
        {

            for (int i = 0; i < (Tasks.Count); i++)
            {                
                dataGridViewTask.Rows[i].Cells[0].Value = i + 1;
                Tasks[i].iTaskNum = i + 1;
            }
        }

        private void buttonAESString_Click(object sender, EventArgs e)
        {
            //Get or show current AES String
            var dictionary = new Dictionary<string, string>();
            dictionary.Add("AES string", Convert.ToBase64String(aes.Key));
            FormParameters formParameter = new FormParameters(dictionary, richTextBoxOutput.Text,
                string.Format("{0}: {1}", "EAS String", "Edit to update with a different EAS String"));


            if (formParameter.ShowDialog() == DialogResult.Cancel)
            {
                log.Info("AES formParameter returns with Cancel");               
            }
            else
            {
                try
                {
                    aes.Key = Convert.FromBase64String(formParameter.dParameters["AES string"]);

                    //try reloading Profilefilename
                    Profiles.Clear();
                    Profiles = utilities.LoadProfile(Profilefilename, aes);
                    // Configure Profile list to dropdown menu, first to check if Profiles is empty
                    if (!Profiles.Any())
                    {
                        //load "do nothing" to Profiles
                        Profile temp = new Profile();
                        temp.ProfileType = "";
                        temp.ProfileName = "Do nothing";
                        temp.ProfileCommands = new string[] { "echo  Do nothing" };
                        temp.ProfileParameters = new string[]{ "" };

                        Profiles.Add(temp);
                    }
                    
                    try
                    {
                        foreach (Profile p in Profiles)
                        {
                            log.Info(string.Format("Profile: {0}", p.ProfileName));
                        }

                        var comboBoxColumn = (DataGridViewComboBoxColumn)dataGridViewTask.Columns[7];
                        comboBoxColumn.DataSource = Profiles; // Set the data source of the ComboBox column
                        comboBoxColumn.DisplayMember = "profileName"; // Displayed property name
                        comboBoxColumn.ValueMember = "profileName"; //The property name of the value
                    }
                    catch (Exception ex)
                    {
                        log.Error(ex.Message);
                    }
                    
                    dataGridViewTask.Refresh();
                }
                catch
                {
                    log.Error("Cannot load AES key");
                }
            }


            //reload tasklist 
            buttonLoad_Click(null, null);
        }
    }

}