// This application can also be started with a command line for automation
// Use following syntax: "monkeyking.exe /<Computername>:<TestName> /<Computername>:<TestName>"
// eg. "MonkeyKing.exe /Pc015:AutomatedTesting /Pc126:AutomatedTesting"
// At the moment u can also just give the "/AutoTest" and every available client will execute the tast "automatedTesting"


using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Net;
using System.Windows.Forms.Design;
using System.Threading;

namespace MonkeyKing
{	/*public class CTestsOfClient
	{

	}*/
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
    public class CMonkeyKing : System.Windows.Forms.Form
    {
        private System.Windows.Forms.Button btn_StartTask;
        private System.Windows.Forms.CheckedListBox clb_SelectClients;
        private System.Windows.Forms.CheckBox cb_AutomatedTesting;
        private System.Windows.Forms.CheckBox cb_CheckGame;
        private System.Windows.Forms.CheckBox cb_CheckFPS;
        private string[,] ga_clientConfig;
        private string[] ga_levels;
        private string[] ga_cmdArgs = Environment.GetCommandLineArgs();
        private static int g_cmdArgsLength;
        private string gs_fileDirectory = Directory.GetCurrentDirectory() + @"\MonkeyKingSysFiles\";
        private string gs_clientsFile = Directory.GetCurrentDirectory() + @"\MonkeyKingSysFiles\clients.txt";
        private string gs_levelsFile = @"\\storage\ExportList\levels.txt";
        //private string gs_levelsFile = Directory.GetCurrentDirectory() + @"\MonkeyKingSysFiles\levels.txt";
        private string gs_errorFile = Directory.GetCurrentDirectory() + @"\MonkeyKingSysFiles\ERROR.txt";
        private System.Windows.Forms.CheckBox cb_ExportLevels;
        private static StreamWriter sw_error = null;
        private RadioButton m_SpecificBuild;
        private RadioButton m_LatestBuild;
        private GroupBox m_BuildSourceGroup;
        private TextBox m_BuildPath;
        private Button m_BrowseBuilds;
        private ToolTip m_TipLatestBuild;
        private ToolTip m_TipSpecificBuild;
        private RadioButton m_LatestApproved;
        private ToolTip m_TipLatestApproved;
        private IContainer components;

        public CMonkeyKing()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            m_TipLatestBuild.SetToolTip(m_LatestBuild, "Will test the absolute latest build available.");
            m_TipLatestApproved.SetToolTip(m_LatestApproved, "Will test the latest approved build available.");
            m_TipSpecificBuild.SetToolTip(m_SpecificBuild, "Please browse for the build folder of the build you want to have tested");
            g_cmdArgsLength = ga_cmdArgs.Length;
            int g_TestOptionsCount = 4;

            //
            // TODO: Add any constructor code after InitializeComponent call
            //

            // If only one argument was given(only the reference to the program itself) start in normal mode
            if (g_cmdArgsLength <= 1)
            {
                ReadClientsFromFile();

                // Set the index of the checked list box to the first item
                clb_SelectClients.SelectedIndex = 0;
                // Create an array for saving the checked options with the same size as the count of online Clients
                this.ga_clientConfig = new string[clb_SelectClients.Items.Count, g_TestOptionsCount];
            }
            else if (ga_cmdArgs[1].ToString().ToLower().IndexOf(@"/export") != -1)
            {
                // Create the error file
                sw_error = File.CreateText(gs_errorFile);
                sw_error.AutoFlush = true;
                ReadClientsFromFile();

                // Create an array for saving the checked options with the same size as the count of online Clients
                this.ga_clientConfig = new string[clb_SelectClients.Items.Count, g_TestOptionsCount];
                // Set the index to the first Client in the checked list box and set the state of it to "checked"
                clb_SelectClients.SelectedIndex = 0;
                clb_SelectClients.SetItemChecked(0, true);

                // Set the tests for the first client
                cb_ExportLevels.CheckState = System.Windows.Forms.CheckState.Checked;

                // Create the Taskfile
                StartTasks();

                // And exit
                Environment.Exit(0);
            }
            else
            {
                // Some Variables
                string s_clientCompName = "";
                char[] a_splitChars = { ',', ':' };

                // Create the error file
                sw_error = File.CreateText(gs_errorFile);

                // Create global array where Clients and its to be performed test are stored
                this.ga_clientConfig = new string[g_cmdArgsLength, g_TestOptionsCount];

                // Go through user given Arguments
                for (int i = 1; i < g_cmdArgsLength; i++)
                {
                    //  Extract the Computer name from the Argument
                    s_clientCompName = ga_cmdArgs[i].Substring(ga_cmdArgs[i].IndexOf(@"/") + 1, ga_cmdArgs[i].IndexOf(@":", 0) - 1);
                    // Check if Client is online and add it to the checked list box if so
                    if (IsClientOnline(s_clientCompName))
                    {
                        // Set the index to the current object in the checked list box and set this items state to "checked"
                        clb_SelectClients.SelectedIndex = i - 1;
                        clb_SelectClients.SetItemChecked(i - 1, true);

                        // Split all tests
                        string[] a_clientTests = ga_cmdArgs[i].Split(a_splitChars, 4);
                        // Go thourgh all splitted strings and check wheter they're test, if so then set the test to "checked"
                        for (int j = 1; j < a_clientTests.Length; j++)
                        {
                            string clientTest = a_clientTests[j];
                            clientTest = clientTest.ToLower();
                            if (clientTest == "checkgame")
                                cb_CheckGame.CheckState = System.Windows.Forms.CheckState.Checked;

                            if (clientTest == "checkeditor")
                                cb_AutomatedTesting.CheckState = System.Windows.Forms.CheckState.Checked;

                            if (clientTest == "checkfps")
                                cb_CheckFPS.CheckState = System.Windows.Forms.CheckState.Checked;

                            if (clientTest == "export")
                                cb_ExportLevels.CheckState = System.Windows.Forms.CheckState.Checked;
                        }
                    }
                }
                // Create the Taskfile
                StartTasks();

                // Close the error file
                if (sw_error != null)
                    sw_error.Close();

                // And exit
                Environment.Exit(0);
            }
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(CMonkeyKing));
            this.btn_StartTask = new System.Windows.Forms.Button();
            this.clb_SelectClients = new System.Windows.Forms.CheckedListBox();
            this.cb_AutomatedTesting = new System.Windows.Forms.CheckBox();
            this.cb_CheckGame = new System.Windows.Forms.CheckBox();
            this.cb_CheckFPS = new System.Windows.Forms.CheckBox();
            this.cb_ExportLevels = new System.Windows.Forms.CheckBox();
            this.m_SpecificBuild = new System.Windows.Forms.RadioButton();
            this.m_LatestBuild = new System.Windows.Forms.RadioButton();
            this.m_BuildSourceGroup = new System.Windows.Forms.GroupBox();
            this.m_LatestApproved = new System.Windows.Forms.RadioButton();
            this.m_BuildPath = new System.Windows.Forms.TextBox();
            this.m_BrowseBuilds = new System.Windows.Forms.Button();
            this.m_TipLatestBuild = new System.Windows.Forms.ToolTip(this.components);
            this.m_TipSpecificBuild = new System.Windows.Forms.ToolTip(this.components);
            this.m_TipLatestApproved = new System.Windows.Forms.ToolTip(this.components);
            this.m_BuildSourceGroup.SuspendLayout();
            this.SuspendLayout();
            // 
            // btn_StartTask
            // 
            this.btn_StartTask.Location = new System.Drawing.Point(55, 245);
            this.btn_StartTask.Name = "btn_StartTask";
            this.btn_StartTask.Size = new System.Drawing.Size(184, 56);
            this.btn_StartTask.TabIndex = 0;
            this.btn_StartTask.Text = "Start Task";
            this.btn_StartTask.Click += new System.EventHandler(this.btn_StartTasks_Click);
            // 
            // clb_SelectClients
            // 
            this.clb_SelectClients.Location = new System.Drawing.Point(12, 114);
            this.clb_SelectClients.Name = "clb_SelectClients";
            this.clb_SelectClients.Size = new System.Drawing.Size(167, 124);
            this.clb_SelectClients.TabIndex = 3;
            this.clb_SelectClients.SelectedIndexChanged += new System.EventHandler(this.clb_SelectClients_SelectedIndexChanged);
            // 
            // cb_AutomatedTesting
            // 
            this.cb_AutomatedTesting.Location = new System.Drawing.Point(192, 118);
            this.cb_AutomatedTesting.Name = "cb_AutomatedTesting";
            this.cb_AutomatedTesting.Size = new System.Drawing.Size(144, 24);
            this.cb_AutomatedTesting.TabIndex = 4;
            this.cb_AutomatedTesting.Text = "Automated Testing";
            this.cb_AutomatedTesting.Visible = false;
            this.cb_AutomatedTesting.CheckedChanged += new System.EventHandler(this.cb_CheckEditor_CheckedChanged);
            // 
            // cb_CheckGame
            // 
            this.cb_CheckGame.Enabled = false;
            this.cb_CheckGame.Location = new System.Drawing.Point(192, 148);
            this.cb_CheckGame.Name = "cb_CheckGame";
            this.cb_CheckGame.Size = new System.Drawing.Size(136, 24);
            this.cb_CheckGame.TabIndex = 5;
            this.cb_CheckGame.Text = "Load Levels in Game";
            this.cb_CheckGame.Visible = false;
            this.cb_CheckGame.CheckedChanged += new System.EventHandler(this.cb_CheckGame_CheckedChanged);
            // 
            // cb_CheckFPS
            // 
            this.cb_CheckFPS.Location = new System.Drawing.Point(192, 178);
            this.cb_CheckFPS.Name = "cb_CheckFPS";
            this.cb_CheckFPS.Size = new System.Drawing.Size(120, 24);
            this.cb_CheckFPS.TabIndex = 6;
            this.cb_CheckFPS.Text = "FPS check";
            this.cb_CheckFPS.Visible = false;
            this.cb_CheckFPS.CheckedChanged += new System.EventHandler(this.cb_CheckFPS_CheckedChanged);
            // 
            // cb_ExportLevels
            // 
            this.cb_ExportLevels.Location = new System.Drawing.Point(192, 208);
            this.cb_ExportLevels.Name = "cb_ExportLevels";
            this.cb_ExportLevels.Size = new System.Drawing.Size(120, 24);
            this.cb_ExportLevels.TabIndex = 7;
            this.cb_ExportLevels.Text = "ExportLevels";
            this.cb_ExportLevels.CheckedChanged += new System.EventHandler(this.cb_ExportLevels_CheckedChanged);
            // 
            // m_SpecificBuild
            // 
            this.m_SpecificBuild.AutoSize = true;
            this.m_SpecificBuild.Location = new System.Drawing.Point(6, 42);
            this.m_SpecificBuild.Name = "m_SpecificBuild";
            this.m_SpecificBuild.Size = new System.Drawing.Size(89, 17);
            this.m_SpecificBuild.TabIndex = 8;
            this.m_SpecificBuild.Text = "Specific Build";
            this.m_SpecificBuild.UseVisualStyleBackColor = true;
            this.m_SpecificBuild.CheckedChanged += new System.EventHandler(this.radioButton1_CheckedChanged);
            // 
            // m_LatestBuild
            // 
            this.m_LatestBuild.AutoSize = true;
            this.m_LatestBuild.Checked = true;
            this.m_LatestBuild.Location = new System.Drawing.Point(6, 19);
            this.m_LatestBuild.Name = "m_LatestBuild";
            this.m_LatestBuild.Size = new System.Drawing.Size(79, 17);
            this.m_LatestBuild.TabIndex = 9;
            this.m_LatestBuild.TabStop = true;
            this.m_LatestBuild.Text = "Latest build";
            this.m_LatestBuild.UseVisualStyleBackColor = true;
            this.m_LatestBuild.CheckedChanged += new System.EventHandler(this.m_LatestBuild_CheckedChanged);
            // 
            // m_BuildSourceGroup
            // 
            this.m_BuildSourceGroup.Controls.Add(this.m_LatestApproved);
            this.m_BuildSourceGroup.Controls.Add(this.m_BuildPath);
            this.m_BuildSourceGroup.Controls.Add(this.m_BrowseBuilds);
            this.m_BuildSourceGroup.Controls.Add(this.m_LatestBuild);
            this.m_BuildSourceGroup.Controls.Add(this.m_SpecificBuild);
            this.m_BuildSourceGroup.Location = new System.Drawing.Point(12, 12);
            this.m_BuildSourceGroup.Name = "m_BuildSourceGroup";
            this.m_BuildSourceGroup.Size = new System.Drawing.Size(295, 96);
            this.m_BuildSourceGroup.TabIndex = 12;
            this.m_BuildSourceGroup.TabStop = false;
            this.m_BuildSourceGroup.Text = "Build source";
            this.m_BuildSourceGroup.Enter += new System.EventHandler(this.m_BuildSourceGroup_Enter);
            // 
            // m_LatestApproved
            // 
            this.m_LatestApproved.AutoSize = true;
            this.m_LatestApproved.Location = new System.Drawing.Point(152, 19);
            this.m_LatestApproved.Name = "m_LatestApproved";
            this.m_LatestApproved.Size = new System.Drawing.Size(127, 17);
            this.m_LatestApproved.TabIndex = 14;
            this.m_LatestApproved.TabStop = true;
            this.m_LatestApproved.Text = "Latest approved build";
            this.m_LatestApproved.UseVisualStyleBackColor = true;
            this.m_LatestApproved.CheckedChanged += new System.EventHandler(this.m_latestApproved_CheckedChanged);
            // 
            // m_BuildPath
            // 
            this.m_BuildPath.Location = new System.Drawing.Point(6, 65);
            this.m_BuildPath.Name = "m_BuildPath";
            this.m_BuildPath.ReadOnly = true;
            this.m_BuildPath.Size = new System.Drawing.Size(221, 20);
            this.m_BuildPath.TabIndex = 13;
            // 
            // m_BrowseBuilds
            // 
            this.m_BrowseBuilds.BackColor = System.Drawing.SystemColors.ButtonFace;
            this.m_BrowseBuilds.Enabled = false;
            this.m_BrowseBuilds.Location = new System.Drawing.Point(233, 65);
            this.m_BrowseBuilds.Name = "m_BrowseBuilds";
            this.m_BrowseBuilds.Size = new System.Drawing.Size(56, 22);
            this.m_BrowseBuilds.TabIndex = 12;
            this.m_BrowseBuilds.Text = "Browse";
            this.m_BrowseBuilds.UseVisualStyleBackColor = false;
            this.m_BrowseBuilds.Click += new System.EventHandler(this.m_BrowseBuilds_Click);
            // 
            // m_TipLatestBuild
            // 
            this.m_TipLatestBuild.Popup += new System.Windows.Forms.PopupEventHandler(this.toolTip1_Popup);
            // 
            // m_TipSpecificBuild
            // 
            this.m_TipSpecificBuild.Popup += new System.Windows.Forms.PopupEventHandler(this.m_TipSpecificBuild_Popup);
            // 
            // m_TipLatestApproved
            // 
            this.m_TipLatestApproved.Popup += new System.Windows.Forms.PopupEventHandler(this.m_TipLatestApproved_Popup);
            // 
            // CMonkeyKing
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(313, 313);
            this.Controls.Add(this.m_BuildSourceGroup);
            this.Controls.Add(this.cb_ExportLevels);
            this.Controls.Add(this.cb_CheckFPS);
            this.Controls.Add(this.cb_CheckGame);
            this.Controls.Add(this.cb_AutomatedTesting);
            this.Controls.Add(this.clb_SelectClients);
            this.Controls.Add(this.btn_StartTask);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.MaximizeBox = false;
            this.Name = "CMonkeyKing";
            this.Text = "MonkeyKing";
            this.Load += new System.EventHandler(this.CMonkeyKing_Load);
            this.m_BuildSourceGroup.ResumeLayout(false);
            this.m_BuildSourceGroup.PerformLayout();
            this.ResumeLayout(false);

        }
        #endregion

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Show an error if the application was started without arguments and no clients.txt exists
            if (!File.Exists(Directory.GetCurrentDirectory() + @"\MonkeyKingSysFiles\clients.txt") && args.Length <= 0)
            {
                MessageBox.Show("Could not find the file " + Directory.GetCurrentDirectory() + @"\MonkeyKingSysFiles\clients.txt", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(1);
            }
            else
                Application.Run(new CMonkeyKing());
        }

        private void ReadClientsFromFile()
        {
            string s_line = "";

            // Read Line from the Clients file
            StreamReader sr_clients = File.OpenText(gs_clientsFile);
            s_line = ReadLineFromFile(sr_clients);
            sr_clients.Close();

            // Check if file is emtpy
            if (s_line == null)
            {
                ErrorExit("File " + gs_clientsFile + " is empty. No clients specified.");
            }

            // Reset the streamreader to read from beginning again  
            sr_clients = File.OpenText(gs_clientsFile);

            do
            {
                // Read a Client from ClientFile
                s_line = ReadLineFromFile(sr_clients);
                // Jump out if line is empty
                if (s_line == null)
                {
                    break;
                }
                // Check if Client is online and add it to the checked list box
                IsClientOnline(s_line);
            } while (s_line != null);

            // Close the client file
            sr_clients.Close();

            // If no clients are online
            if (clb_SelectClients.Items.Count == 0)
            {
                ErrorExit("Could not find any online clients.");
            }
        }

        // Will Exit with/without a message box
        private bool ErrorExit(string s_errorMsg)
        {
            if (g_cmdArgsLength >= 2)
                WriteLineToFile(s_errorMsg);
            else
                MessageBox.Show(s_errorMsg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            if (sw_error != null)
                sw_error.Close();

            Environment.Exit(1);

            return true;
        }

        // Will Exit with/without a message box
        private static bool Echo(string s_msg)
        {
            if (g_cmdArgsLength >= 2)
                WriteLineToFile(s_msg);
            else
                MessageBox.Show(s_msg, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);

            return true;
        }

        // Function for checking wheter a given client is online
        private bool IsClientOnline(string s_computerName)
        {
            bool active = true;

            // Create the link to the Client.txt on the clients PC with the Clientname in it
            string s_clientNameFile = @"\\" + s_computerName + @"\MonkeyKing\client.txt";
            string s_clientName = null;

            // Create the link to the ActiveFalg.txt on the clients PC with the last active time in it
            string s_activeFlagFile = @"\\" + s_computerName + @"\MonkeyKing\ActiveFlag.txt";
            string s_activeTime = null;

            // Check if the flag file exists on client
            if (File.Exists(s_activeFlagFile))
            {
                int i_readTrys = 0;
                int i_readTrys_max = 30;
                // Check if client is active(active flag is not older then 5 min)
                // Read in the file
                do
                {
                    try
                    {
                        i_readTrys++;
                        StreamReader sr_activeTime = File.OpenText(s_activeFlagFile);
                        //FileInfo.CopyTo() //maybe an alternativ way for reading if file is in use
                        s_activeTime = ReadLineFromFile(sr_activeTime);
                        sr_activeTime.Close();
                    }
                    catch (Exception e)
                    {                        
                        if (i_readTrys >= i_readTrys_max)
                        {
                            string s_temp = "Can't read active flag file " + s_activeFlagFile;
                            s_temp += "\nException: " + e.Message + "\n" + e.Source;
                            Echo(s_temp);
                        }
                        else
                        {
                           // Thread.Sleep(100);
                        }
                            
                    }
                } while (i_readTrys < i_readTrys_max);

                // Exit if file is empty
                if (s_activeTime == null)
                {
                    active = false;
                }
                else
                {
                    // Create a custom date string				
                    DateTime now = DateTime.Now;
                    System.TimeSpan timeOut = new TimeSpan(0, 5, 0);
                    DateTime nowMinusTimout = now.Subtract(timeOut);
                    try
                    {
                        DateTime d_activeTime = DateTime.Parse(s_activeTime);

                        // if last active time is older then 5 min. then the client is not active
                        if (DateTime.Compare(nowMinusTimout, d_activeTime) > 0)
                        {
                            active = false;
                        }
                    }
                    catch (Exception e)
                    {
                        string s_temp2 = "The input from the active flag file " + s_activeFlagFile;
                        s_temp2 += " was not in the right format or didn't provide the necessary information.";
                        Echo(s_temp2);
                        active = false;
                    }
                }

                
            }
            else
            {
                active = false;
            }

            if (!active)
            {
                // Log the error if the client is not online
                Echo("Client " + s_computerName + " is not active");
                return (false);
            }



            // Check if the client name file exists on client
            if (File.Exists(s_clientNameFile))
            {
                // Read Clientname of client/
                StreamReader sr_clientName = File.OpenText(s_clientNameFile);
                s_clientName = ReadLineFromFile(sr_clientName);
                sr_clientName.Close();
                if (s_clientName == null)
                {
                    // Log the error if the client is not online
                    Echo("Client " + s_computerName + " is not online");
                    return (false);
                }
                // Add client name to CheckedListBox
                clb_SelectClients.Items.Add(s_computerName + @"_" + s_clientName);
                return (true);
            }
            else
            {
                // Log the error if the client is not online
                Echo("Client " + s_computerName + " is not online");
                return (false);
            }

            
        }

        // Function for reading from a stream
        private static string ReadLineFromFile(StreamReader sr_stream)
        {
            string s_input = null;
            try 
            {
                s_input = sr_stream.ReadLine();
            }
            catch (Exception e)
            {
                Echo("Couldn't read file becuase of : ");//+ e.ToString()
            }

            return (s_input);
        }

        // Function for writing to the error file
        private static void WriteLineToFile(string error)
        {
            sw_error.WriteLine(error);
        }

        // Creates the Taskfile
        private void StartTasks()
        {
            string dlgBuildPath = m_BuildPath.Text;

            // Check if at least one client is checked 
            if (clb_SelectClients.CheckedItems.Count >= 1)
            {
                int tempBuildNumber = 0;
                int numberLength = 0;
                //string finalBuildName = "";
                string finalBuildPath = "";
                string dateToFile = "";

                if (m_SpecificBuild.Checked)
                {
                    if (dlgBuildPath.StartsWith(@"\\"))
                    {
                        if (dlgBuildPath != "")
                        {
                            // Extract the build name from the string
                            int lastSlash = 0;
                            int leftParenthesis = 0;
                            int rightParenthesis = 0;

                            lastSlash = dlgBuildPath.LastIndexOf(@"\");
                            rightParenthesis = dlgBuildPath.IndexOf(")", lastSlash);
                            leftParenthesis = dlgBuildPath.IndexOf("(", lastSlash);
                            numberLength = (rightParenthesis - leftParenthesis) - 1;
                            if (numberLength >= 1 || dlgBuildPath[rightParenthesis + 1].CompareTo('_') == 0)
                            {
                                //finalBuildName = dlgBuildPath.Substring(lastSlash + 1, dlgBuildPath.Length - lastSlash - 1);
                                try
                                {
                                    tempBuildNumber = int.Parse(dlgBuildPath.Substring(leftParenthesis + 1, numberLength));
                                    finalBuildPath = dlgBuildPath;
                                }
                                catch (Exception e)
                                {
                                    Echo("You've not selected a valid build");
                                    return;
                                }
                            }
                            else
                            {
                                Echo("No builds could be found in the given location!");
                                return;
                            }
                        }
                        else
                        {
                            Echo("No build location was given!");
                            return;
                        }
                    }
                    else
                    {
                        Echo("No network computer was choosen!");
                        return;
                    }
                }
                else if (m_LatestBuild.Checked)
                    finalBuildPath = "latest";
                else if (m_LatestApproved.Checked)
                    finalBuildPath = "approved";

                // Create a custom date string				
                DateTime now = DateTime.Now;
                dateToFile = now.Year + "-" + now.Month + "-" + now.Day + " " + now.Hour + ":" + now.Minute + ":" + now.Second;


                string s_levels = "";
                this.ga_levels = new string[clb_SelectClients.CheckedItems.Count];

                // Read all from the levels file
                StreamReader sr_levels = File.OpenText(gs_levelsFile);
                s_levels = sr_levels.ReadToEnd();
                // Close the levels file
                sr_levels.Close();

                if (s_levels == "")
                {
                    ErrorExit("File " + gs_levelsFile + " is empty");
                }

                // Read in the levels file and figure out how many levels a client gets
                string[] stringSeparators = new string[] { "\r\n" };
                ga_levels = s_levels.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);


                if (g_cmdArgsLength > 1)
                {
                    int i_result = 0;
                    int remainder = 0;
                    i_result = Math.DivRem(ga_levels.Length, clb_SelectClients.Items.Count, out remainder);
                    // Will enable the required number of clients
                    if (ga_cmdArgs[1].ToString().ToLower().IndexOf(@"/export") != -1)
                    {
                        if (i_result == 0)
                        {
                            // Enable only a few clients if levels to export are less then the number of clients 
                            for (int i = 0; i < remainder; i++)
                            {
                                clb_SelectClients.SelectedIndex = i;
                                clb_SelectClients.SetItemChecked(i, true);
                                cb_ExportLevels.CheckState = System.Windows.Forms.CheckState.Checked;
                            }
                        }
                        else
                        {
                            // Ebale all clients if at least one client have one level to export
                            int i_ClientsNr = clb_SelectClients.Items.Count;
                            for (int i = 0; i < i_ClientsNr; i++)
                            {
                                clb_SelectClients.SelectedIndex = i;
                                clb_SelectClients.SetItemChecked(i, true);
                                cb_ExportLevels.CheckState = System.Windows.Forms.CheckState.Checked;
                            }
                        }
                    }
                }

                int i_exportingClients = 0;
                foreach (object itemChecked in clb_SelectClients.CheckedItems)
                {
                    if (ga_clientConfig.GetValue(clb_SelectClients.Items.IndexOf(itemChecked), 3) == "1")
                        i_exportingClients++;
                }

                int i_leftLevels = 0;
                int i_nrOfLevelsProClient = Math.DivRem(ga_levels.Length, i_exportingClients, out i_leftLevels);
                int i_levelsIndex = 0;

                // Create a Taskfile for each checked Client
                foreach (object itemChecked in clb_SelectClients.CheckedItems)
                {
                    bool bCheckEditor = false;
                    bool bCheckGame = false;
                    bool bCheckFPS = false;
                    bool bExport = false;
                    bool bTaskGiven = false;

                    if (ga_clientConfig.GetValue(clb_SelectClients.Items.IndexOf(itemChecked), 0) == "1")
                    {
                        bCheckEditor = true;
                        bTaskGiven = true;
                    }

                    if (ga_clientConfig.GetValue(clb_SelectClients.Items.IndexOf(itemChecked), 1) == "1")
                    {
                        bCheckGame = true;
                        bTaskGiven = true;
                    }
                    if (ga_clientConfig.GetValue(clb_SelectClients.Items.IndexOf(itemChecked), 2) == "1")
                    {
                        bCheckFPS = true;
                        bTaskGiven = true;
                    }
                    if (ga_clientConfig.GetValue(clb_SelectClients.Items.IndexOf(itemChecked), 3) == "1")
                    {
                        bExport = true;
                        bTaskGiven = true;
                    }

                    if (bTaskGiven)
                    {
                        StreamWriter sw = new StreamWriter(gs_fileDirectory + itemChecked.ToString() + "_Task.txt");
                        sw.Write(finalBuildPath);
                        sw.Write("\r\n" + dateToFile);
                        if (bCheckEditor)
                            sw.Write("\r\nCheckEditor");

                        if (bCheckGame)
                            sw.Write("\r\nCheckGame");

                        if (bCheckFPS)
                            sw.Write("\r\nCheckFPS");

                        if (bExport)
                        {
                            sw.Write("\r\nExport");

                            for (int i = 1; i <= i_nrOfLevelsProClient; i++, i_levelsIndex++)
                            {
                                sw.Write("\r\nL:" + ga_levels[i_levelsIndex]);
                            }

                            if (i_levelsIndex < ga_levels.Length && i_leftLevels != 0)
                            {
                                sw.Write("\r\nL:" + ga_levels[i_levelsIndex]);
                                i_levelsIndex++;
                            }
                        }

                        sw.Close();
                    }
                }

                // Overwrite the levels file with an empty one
                StreamWriter sw_levels = new StreamWriter(gs_levelsFile);
                // Close the levels file
                sw_levels.Close();

                Echo("Testing task was written into file. Client will start testing soon.");
            }
            else
                Echo("No client selected");
        }

        private void btn_StartTasks_Click(object sender, System.EventArgs e)
        {
            StartTasks();
        }

        // Show the selected testing options for currently selected client
        private void clb_SelectClients_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            // Check against crash because else this would be executed before ga_clientConfig was defined
            if (ga_clientConfig != null)
            {
                if (ga_clientConfig.GetValue(clb_SelectClients.SelectedIndex, 0) == "1")
                {
                    cb_AutomatedTesting.CheckState = System.Windows.Forms.CheckState.Checked;
                }
                else
                {
                    cb_AutomatedTesting.CheckState = System.Windows.Forms.CheckState.Unchecked;
                }

                if (ga_clientConfig.GetValue(clb_SelectClients.SelectedIndex, 1) == "1")
                {
                    cb_CheckGame.CheckState = System.Windows.Forms.CheckState.Checked;
                }
                else
                {
                    cb_CheckGame.CheckState = System.Windows.Forms.CheckState.Unchecked;
                }

                if (ga_clientConfig.GetValue(clb_SelectClients.SelectedIndex, 2) == "1")
                {
                    cb_CheckFPS.CheckState = System.Windows.Forms.CheckState.Checked;
                }
                else
                {
                    cb_CheckFPS.CheckState = System.Windows.Forms.CheckState.Unchecked;
                }

                if (ga_clientConfig.GetValue(clb_SelectClients.SelectedIndex, 3) == "1")
                {
                    cb_ExportLevels.CheckState = System.Windows.Forms.CheckState.Checked;
                }
                else
                {
                    cb_ExportLevels.CheckState = System.Windows.Forms.CheckState.Unchecked;
                }
            }
        }

        private void cb_CheckEditor_CheckedChanged(object sender, System.EventArgs e)
        {
            if (cb_AutomatedTesting.Checked)
            {
                ga_clientConfig.SetValue("1", clb_SelectClients.SelectedIndex, 0);
            }
            else
            {
                ga_clientConfig.SetValue("0", clb_SelectClients.SelectedIndex, 0);
            }

        }

        private void cb_CheckGame_CheckedChanged(object sender, System.EventArgs e)
        {
            if (cb_CheckGame.Checked)
            {
                ga_clientConfig.SetValue("1", clb_SelectClients.SelectedIndex, 1);
            }
            else
            {
                ga_clientConfig.SetValue("0", clb_SelectClients.SelectedIndex, 1);
            }
        }

        private void cb_CheckFPS_CheckedChanged(object sender, System.EventArgs e)
        {
            if (cb_CheckFPS.Checked)
            {
                ga_clientConfig.SetValue("1", clb_SelectClients.SelectedIndex, 2);
            }
            else
            {
                ga_clientConfig.SetValue("0", clb_SelectClients.SelectedIndex, 2);
            }
        }

        private void cb_ExportLevels_CheckedChanged(object sender, System.EventArgs e)
        {
            if (cb_ExportLevels.Checked)
            {
                ga_clientConfig.SetValue("1", clb_SelectClients.SelectedIndex, 3);
            }
            else
            {
                ga_clientConfig.SetValue("0", clb_SelectClients.SelectedIndex, 3);
            }
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            if (m_SpecificBuild.Checked)
                m_BrowseBuilds.Enabled = true;
        }

        private void folderBrowserDialog1_HelpRequest(object sender, EventArgs e)
        {

        }

        private void CMonkeyKing_Load(object sender, EventArgs e)
        {

        }

        private void m_BuildPath_TextChanged(object sender, EventArgs e)
        {

        }

        private void m_BrowseBuilds_Click(object sender, EventArgs e)
        {
            DirBrowser Dialog = new DirBrowser();
            if (Dialog.ShowDialog() == DialogResult.OK)
                m_BuildPath.Text = Dialog.ReturnPath;
        }

        private void toolTip1_Popup(object sender, PopupEventArgs e)
        {

        }

        private void m_BuildSourceGroup_Enter(object sender, EventArgs e)
        {

        }

        private void m_TipSpecificBuild_Popup(object sender, PopupEventArgs e)
        {

        }

        private void m_LatestBuild_CheckedChanged(object sender, EventArgs e)
        {
            if (m_LatestBuild.Checked)
                m_BrowseBuilds.Enabled = false;
        }

        private void folderBrowserDialog1_HelpRequest_1(object sender, EventArgs e)
        {

        }

        private void m_latestApproved_CheckedChanged(object sender, EventArgs e)
        {
            if (m_LatestApproved.Checked)
                m_BrowseBuilds.Enabled = false;
        }

        private void m_TipLatestApproved_Popup(object sender, PopupEventArgs e)
        {

        }


    }
  public class DirBrowser : FolderNameEditor
  {
    FolderBrowser fb = new FolderBrowser();

    public string Description
    {
      set { _description = value; }
      get { return _description; }
    }

    public string ReturnPath
    {
      get { return _returnPath; }
    }

    public DirBrowser() { }

    private DialogResult RunDialog()
    {
      fb.Description = this.Description;
      fb.StartLocation = FolderBrowserFolder.NetworkNeighborhood;
      fb.Style = FolderBrowserStyles.BrowseForComputer ;

      DialogResult r = fb.ShowDialog();
      if (r == DialogResult.OK)
        _returnPath = fb.DirectoryPath;
      else
        _returnPath = String.Empty;

      return r;
    }

    public DialogResult ShowDialog()
    {
      return RunDialog();
    }

    private string _description = "Choose Directory";
    private string _returnPath = String.Empty;

  }
}
